File tree Expand file tree Collapse file tree 1 file changed +30
-4
lines changed Expand file tree Collapse file tree 1 file changed +30
-4
lines changed Original file line number Diff line number Diff line change 1
1
use v6 ;
2
2
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 {
5
29
my \u = N * (N - 2 * a);
6
30
my \v = 2 * (N - a);
7
31
32
+ # check if b = u/v is an integer
33
+ # if so, we've found a triple
8
34
if u %% v {
9
35
my \b = u div v;
10
36
my \c = N - a - b;
11
- return a, b, c;
37
+ take $ ( a, b, c) ;
12
38
}
13
39
}
14
40
}
15
41
16
- say [* ] first-triple (1000 );
42
+ say [* ] . list for gather triples (1000 );
You can’t perform that action at this time.
0 commit comments