1. 程式人生 > >[Perl 6][Project Euler] Problem 9 - Special Pythagorean triplet

[Perl 6][Project Euler] Problem 9 - Special Pythagorean triplet

spc tid int exists post auto gsp none style

[Perl 6][Project Euler] Problem 9 - Special Pythagorean triplet

Description

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a^2 + b^2 = c^2

For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Code

constant n = 1000;
constant sup = Int((1 - sqrt(0.5)) * n);

say [*] flat gather for 1..sup -> \a {
    my \u = n * (n - 2 * a);
    my \v = 2 * (n - a);
    take a, u / v, n - a - u / v if u %% v;
}

Explanation

(0) n = 1000

(1) a < b < c

(2) a + b + c = n

(3) a^2 + b^2 = c^2

(4) b = n(n - 2a) / 2(n - a)

(5) c = n(n - 2a) / 2(n - a) + a^2 / (n - a) = n - a - b

?

[Perl 6][Project Euler] Problem 9 - Special Pythagorean triplet