Special pythagorean triplet: Difference between revisions
→{{header|ALGOL 68}}: Make better use of Euclid's formula to reduce the possible candidates.
m (→{{header|Phix}}: or -> and not) |
(→{{header|ALGOL 68}}: Make better use of Euclid's formula to reduce the possible candidates.) |
||
Line 7:
<br><br>
=={{header|ALGOL 68}}==
Uses Euclid's formula, as in the XPL0 sample but also uses the fact that M and N must be factors of half the triangle's perimeter to reduce the number of candidate M's to check. A loop is not needed to find N once a candidate M has been found.
<lang algol68>BEGIN # find the product of the of the Pythagorian triplet a, b, c where: #
# a + b + c = 1000, a2 + b2 = c2, a < b < c #
INT
INT half perimeter = perimeter OVER 2;
INT max factor
FOR m WHILE m < max factor DO
# a = m^2 - n^2, b = 2mn, c = m^2 + n^2 ( Euclid's formula ), so #▼
# using Euclid's formula:
# a = m^2
# a + b + c = m^2
# so m and ( m + n
IF half perimeter MOD
# have a factor
INT other factor = half perimeter OVER m;
print( ( "a = ", whole( a, 0 ), ", b = ", whole( b, 0 ), ", c = ", whole( c, 0 ), newline ) );▼
INT n
INT m2 = m * m, n2 = n * n;
INT a := IF m > n THEN m2 - n2 ELSE n2 - m2 FI;
INT b := 2 * m * n;
INT c = m2 + n2;
IF ( a + b + c ) /= perimeter THEN
# the pythagorean triple formed from m and n is not #
# the triple we are looking for - we now need only search #
max factor := other factor
ELSE
# have found the reuired triple #
IF b < a THEN INT t = a; a := b; b := t FI;
print( ( "; a * b * c = ", whole( a * b * c, 0 ), newline ) );
# no need to search further #
max factor := 0
FI
OD
END</lang>
{{out}}
<pre>
a =
</pre>
|