aboutsummaryrefslogtreecommitdiff
path: root/challenge-148/e-choroba/perl/ch-2.pl
blob: e453b21073ccf720c4c17de6ad434c6b01aec3f2 (plain)
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
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

# https://stackoverflow.com/a/70414782/1030675
sub cardano_triplets {
    my ($count) = @_;
    for (my $u = 1; $count--; $u += 2) {
        my $A = (1 + 3 * $u) / 2;
        my $t = $u * $u * $u + $A * $A;

        my $B = int sqrt $t;
        --$B while $t % ($B * $B);

        my $C = $t / ($B * $B);

        say "$A $B $C";
    }
}

# This finds all the triplets, but they aren't sorted so nicely.
sub cardano_triplets_all {
    my ($count) = @_;
    for (my $u = 1;; $u += 2) {
        my $A = (1 + 3 * $u) / 2;
        my $t = $u * $u * $u + $A * $A;

        my $B = int sqrt $t;
        while (1) {
            --$B while $B && $t % ($B * $B);
            last unless $B;

            my $C = $t / ($B * $B);
            say "$A $B $C";
            return unless --$count;

            --$B;
        }
    }
}

cardano_triplets(5);
say '-' x 10;
cardano_triplets_all(5);