Amicable pairs: Difference between revisions

→‎{{header|ALGOL 68}}: Simplify and particularly use a better method to calculate the proper divisor sum table
(→‎{{header|ALGOL 68}}: Simplify and particularly use a better method to calculate the proper divisor sum table)
Line 601:
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68"># returns the sum of the proper divisors of n #
BEGIN # find amicable pairs p1, p2 where each is equal to the other's proper divisor sum #
# if n = 1, 0 or -1, we return 0 #
[ END1 #: 20 000 ]INT pd sum; # table of proper divisors # ;
PROC sum proper divisors = ( INT n )INT:
FOR n TO UPB proper divisorpd sum DO proper divisorpd sum[ n ] := sum proper divisors( n )1 OD;
BEGIN
FOR i FROM 2 TO INTUPB resultpd := 0;sum
DO INTFOR absj nFROM =i ABS+ n;i BY i TO UPB pd sum DO
IF abs n >pd 1sum[ THENj ] +:= i
BEGIN OD
FOR d FROM ENTIER sqrt( abs n ) BY -1 TO 2 DO
OD;
IF abs n MOD d = 0 THEN
# find the amicable pairs up to 20 000 # found another divisor #
FOR p1 TO UPB pd sum result +:= d;DO
FOR p2 FROM p1 + 1 TO UPB pd sum IF d * d /= n THENDO
IF pd sum[ p1 ] = p2 AND pd sum[ p2 ] = #p1 include the other divisor #THEN
print( ( whole( p1, -6 ), " and ", resultwhole( +:=p2, n-6 OVER), d" are an amicable pair", newline ) )
FI
FIOD
OD;
# 1 is always a proper divisor of numbers > 1 #
result +:= 1
FI;
result
END # sum proper divisors # ;
 
# construct a table of the sum of the proper divisors of numbers #
# up to 20 000 #
INT max number = 20 000;
[ 1 : max number ]INT proper divisor sum;
FOR n TO UPB proper divisor sum DO proper divisor sum[ n ] := sum proper divisors( n ) OD;
 
# returns TRUE if n1 and n2 are an amicable pair FALSE otherwise #
# n1 and n2 are amicable if the sum of the proper diviors #
# n1 = n2 and the sum of the proper divisors of n2 = n1 #
PROC is an amicable pair = ( INT n1, n2 )BOOL:
( proper divisor sum[ n1 ] = n2 AND proper divisor sum[ n2 ] = n1 );
 
# find the amicable pairs up to 20 000 #
FOR p1 TO max number DO
FOR p2 FROM p1 + 1 TO max number DO
IF is an amicable pair( p1, p2 ) THEN
print( ( whole( p1, -6 ), " and ", whole( p2, -6 ), " are an amicable pair", newline ) )
FI
OD
END
OD</syntaxhighlight>
{{out}}
<pre>
3,060

edits