-
Notifications
You must be signed in to change notification settings - Fork 7
/
196 Prime triplets.pl
92 lines (76 loc) · 2.3 KB
/
196 Prime triplets.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
#!/usr/bin/perl
# Author: Daniel "Trizen" Șuteu
# Date: 20 August 2016
# License: GPLv3
# Website: https://github.com/trizen
# https://projecteuler.net/problem=196
# Runtime: 8.838s
use 5.010;
use strict;
use integer;
use ntheory qw(is_prime);
sub vertical {
($_[0]**2 - $_[0] + 2) / 2;
}
sub prime_triples {
my ($n) = @_;
my $up = vertical($n - 1);
my $down = vertical($n + 1);
my $me = vertical($n);
my $upup = vertical($n - 2);
my $downdown = vertical($n + 2);
my @valid = (
[\$me, $me, $me + $n],
[\$up, $up, $up + $n - 1],
[\$down, $down, $down + $n + 1],
[\$upup, $upup, $upup + $n - 2],
[\$downdown, $downdown, $downdown + $n - 2],
);
my @moves = (
[[1, -1], [3, -1]],
[[2, -1], [4, -1]],
[[1, +0], [3, +1]],
[[2, +0], [4, +1]],
[[1, +0], [2, +1]],
[[2, +0], [1, +1]],
[[1, +1], [3, +1]],
[[2, +1], [4, +1]],
[[2, +0], [4, -1]],
[[1, +0], [3, -1]],
[[1, +0], [2, -1]],
[[1, -1], [0, -2]],
[[2, -1], [0, -2]],
[[1, +1], [0, +2]],
[[2, +1], [0, +2]],
[[2, +0], [1, -1]],
[[2, -1], [2, +1]],
[[1, -1], [1, +1]],
[[1, +0], [3, +0]],
[[2, +1], [4, +0]], # this happens only once
);
my $sum = 0;
foreach my $i (1 .. $n) {
if (is_prime($me)) {
OUTER: foreach my $move (@moves) {
foreach my $group (@$move) {
my ($n, $n_min, $n_max) = @{$valid[$group->[0]]};
my $v = $group->[1] + $$n;
if ($v < $n_min or $v > $n_max or not is_prime($v)) {
next OUTER;
}
}
$sum += $me;
last;
}
}
++$up;
++$down;
++$me;
++$upup;
++$downdown;
}
$sum;
}
my $x = prime_triples(5678027);
my $y = prime_triples(7208785);
say "$x + $y = ", $x + $y;