Special pythagorean triplet: Difference between revisions

→‎{{header|ALGOL 68}}: Show the number of iterations reuired and don't stop after the first (only) solution has been found.
(→‎{{header|ALGOL 68}}: Make better use of Euclid's formula to reduce the possible candidates.)
(→‎{{header|ALGOL 68}}: Show the number of iterations reuired and don't stop after the first (only) solution has been found.)
Line 8:
=={{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.
<br>Does not stop after the solution has been found, thus verifying there is only one solution.
<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 #
Line 13 ⟶ 14:
INT half perimeter = perimeter OVER 2;
INT max factor := half perimeter;
INT count ELSE := 0;
FOR m WHILE m < max factor DO
count +:= FI1;
# using Euclid's formula: #
# a = m^2 - n^2, b = 2mn, c = m^2 + n^2 for some integer m, n, so #
Line 26 ⟶ 29:
INT b := 2 * m * n;
INT c = m2 + n2;
IF ( a + b + c ) /= perimeter THEN
# have found the pythagoreanrequired triple formed from m and n is not #
# the triple we are looking for - we now need only search #
# up to at most the other factor #
max factor := other factor
ELSE
# have found the reuired triple #
IF b < a THEN INT t = a; a := b; b := t FI;
print( ( "a = ", whole( a, 0 ), ", b = ", whole( b, 0 ), ", c = ", whole( c, 0 ) ) );
print( ( "; a * b * c = ", whole( a * b * c, 0 ), newline ) );
FI;
# no need to search further #
max factor := 0other factor
FI
FI
OD;
print( ( whole( count, 0 ), " iterations", newline ) )
END</lang>
{{out}}
<pre>
a = 200, b = 375, c = 425; a * b * c = 31875000
24 iterations
</pre>
 
Note that if we stopped after finding the solution, it would be 20 iterations.
 
=={{header|ALGOL W}}==
3,044

edits