-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path516 5-smooth totients.pl
68 lines (56 loc) · 1.25 KB
/
516 5-smooth totients.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/perl
# Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 04 May 2017
# https://github.com/trizen
# https://projecteuler.net/problem=516
# Runtime: 41.831s.
use 5.010;
use strict;
use ntheory qw(
factor
euler_phi
is_prime
);
my @smooth = (1);
my $limit = 1e12;
my $mod = 1 << 32;
foreach my $p (2, 3, 5) {
foreach my $n (@smooth) {
if ($n * $p <= $limit) {
push @smooth, $n * $p;
}
}
}
@smooth =
sort { $b <=> $a }
grep { is_prime($_) }
map { $_ + 1 } @smooth;
my @h = (1);
my $sum = 1;
foreach my $p (@smooth) {
foreach my $n (@h) {
if (
$p * $n <= $limit
and (factor(euler_phi($n * $p)))[-1] <= 5
) {
if ($p == 2) { # optional optimization
foreach my $n (@h) {
while ($n * $p <= $limit) {
$sum += ($n * $p) % $mod;
$sum %= $mod;
$n *= $p;
}
}
last;
}
else {
$sum += ($n * $p) % $mod;
$sum %= $mod;
push @h, $n * $p;
}
}
}
say "$p -> $sum ($#h)";
}
say "Final answer: $sum";