Skip to content

Commit e18dc35

Browse files
committed
[euler/prob009] tighten loop constraint and add explanation
1 parent ff087ef commit e18dc35

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

euler/prob009-gerdr.pl

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,42 @@
11
use v6;
22

3-
sub first-triple(\N) {
4-
for 1..(N div 3) -> \a {
3+
# Let (a, b, c) be a pythagorean triple
4+
#
5+
# a < b < c
6+
# a² + b² = c²
7+
#
8+
# For N = a + b + c it follows
9+
#
10+
# b = N·(N - 2a) / 2·(N - a)
11+
# c = N·(N - 2a) / 2·(N - a) + a²/(N - a)
12+
#
13+
# which automatically meets b < c.
14+
#
15+
# The condition a < b gives the constraint
16+
#
17+
# a < (1 - 1/√2)·N
18+
#
19+
# which we use in the form
20+
#
21+
# a < (2·N - √(2·N²)) / 2
22+
#
23+
# to minimize computational errors.
24+
25+
sub triples(\N) {
26+
my \A = Int(2 * N - sqrt(2 * N * N)) div 2;
27+
28+
for 1..A -> \a {
529
my \u = N * (N - 2 * a);
630
my \v = 2 * (N - a);
731

32+
# check if b = u/v is an integer
33+
# if so, we've found a triple
834
if u %% v {
935
my \b = u div v;
1036
my \c = N - a - b;
11-
return a, b, c;
37+
take $(a, b, c);
1238
}
1339
}
1440
}
1541

16-
say [*] first-triple(1000);
42+
say [*] .list for gather triples(1000);

0 commit comments

Comments
 (0)