-
Notifications
You must be signed in to change notification settings - Fork 7
/
425 Prime connection.pl
104 lines (80 loc) · 2.09 KB
/
425 Prime connection.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/perl
# Daniel "Trizen" Șuteu
# Date: 20 August 2017
# https://github.com/trizen
# https://projecteuler.net/problem=425
# Runtime: 8 min, 23 sec
use 5.010;
use strict;
use ntheory qw(primes);
use List::Util qw(shuffle);
my $limit = 10**7;
# Array of primes up to limit
my @primes = @{primes($limit)};
# Table of primes up to limit
my %h;
@h{@primes} = ();
my %seen;
my %lens;
# Group by length
foreach my $p (@primes) {
push @{$lens{length($p)}}, $p;
}
# Group by difference of one digit
my %table;
foreach my $len (sort { $b <=> $a } keys %lens) {
foreach my $p (@{$lens{$len}}) {
foreach my $i (0 .. $len - 1) {
my $t = $p;
substr($t, $i, 1, 'x');
push @{$table{$t}}, $p;
}
}
}
sub is_twos_relative {
my ($n, $m) = @_;
# If we reach `n=2`, then `m` is a 2's relative
return 1 if $n == 2;
# If `n` was already seen, then `m` is not a 2's relative
if (exists $seen{$n}) {
return 0;
}
undef $seen{$n}; # mark `n` as seen
# If removing one digit from the left is still a prime
if (exists($h{substr($n, 1)})) {
# Is this prime connected to `m` via 2? Great! We're done!
if (is_twos_relative(substr($n, 1), $m)) {
return 1;
}
}
# Create the keys that differ in exactly one digit from n
my @comb;
foreach my $i (0 .. length($n) - 1) {
my $t = $n;
substr($t, $i, 1, 'x');
push @comb, $t;
}
# For each key, iterate over the corresponding primes
foreach my $c (shuffle(@comb)) {
foreach my $p (@{$table{$c}}) {
# We're not interested in p > m
if ($p > $m) {
last;
}
# Is `p` connected to `m` via 2? Great! We're done!
if (is_twos_relative($p, $m)) {
return 1;
}
}
}
return 0;
}
# Sum the primes which are not 2's relatives.
my $sum = 0;
foreach my $p (@primes) {
if (not is_twos_relative($p, $p)) {
$sum += $p;
}
undef %seen; # reset the `seen` table
}
say $sum;