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.
Using Euclid's formula, as in the XPL0 sample.
<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 sqrtperimeter 1000 = ENTIER sqrt( 1000 )= 1000;
INT half perimeter = perimeter OVER 2;
FOR n TO sqrt 1000 DO # m and must have different parity, i.e. one even, one odd #
INT max factor FOR m FROM n:= +half 1 BY 2 TO sqrt 1000 DOperimeter;
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 + b + c = m^2 - n^2 + 2mn + m^2 + n^2 = 2( m^2 + mn ) = 2m( m + n ) # #
# a = m^2 IF- mn^2, *b (= 2mn, c = m^2 + n^2 for some integer m, n, so ) = 500 THEN#
# a + b + c = m^2 INT- m2n^2 =+ m2mn *+ m,^2 n2+ n^2 = n2m( *m + n; ) #
# so m and ( m + n INT) aare =factors m2of -half n2;the perimeter #
IF half perimeter MOD INT bm = 2 * m *0 n;THEN
# have a factor INTof chalf =the m2perimiter + n2; #
INT other factor = half perimeter OVER m;
print( ( "a = ", whole( a, 0 ), ", b = ", whole( b, 0 ), ", c = ", whole( c, 0 ), newline ) );
INT n print( ( "a * b * c = ", whole( a * b * c, 0= ),other newlinefactor )- )m;
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 #
# aup to at most =the m^2other -factor n^2, b = 2mn, c = m^2 + n^2 ( Euclid's formula ), so #
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 ), newline ) );
print( ( "; a * b * c = ", whole( a * b * c, 0 ), newline ) );
# no need to search further #
max factor := 0
FI
ODFI
OD
END</lang>
{{out}}
<pre>
a = 375200, b = 200375, c = 425; a * b * c = 31875000
a * b * c = 31875000
</pre>
 
3,044

edits