Perfect numbers: Difference between revisions

m
Line 673:
]
</lang>
 
=={{header|REXX}}==
===version 1===
<lang rexx>
/*REXX program to test if a number is perfect. */
 
arg low high .
if high=='' & low=='' then high=10000
if low=='' then low=1
if high=='' then high=low
 
do j=low to high
if isperfect(j) then say j 'is a perfect number.'
end
 
exit
 
/*─────────────────────────────────────ISPERFECT subroutine─────────────*/
isperfect: procedure; parse arg x /*get the number to be tested. */
if x=6 then return 1 /*handle this special case. */
if x//2==1 | x<28 then return 0 /*if odd or less then 28, nope. */
 
sum=3+x%2 /*we know the following factors: */
/* 1 */
/* 2 (because it's even.) */
/* x/2 " " " */
 
 
do j=3 to x%2 /*starting at 3, find factors. */
if j*j>x then leave /*if past the sqrt of X, stop. */
if x//j==0 then do /*J divides X evenly, so ... */
sum=sum+j+x%j /*... add it and the other factor*/
end
end
 
return sum==x /*if the sum matches X, perfect! */
</lang>
Output (using the defaults):
<pre style="height:15ex;overflow:scroll">
6 is a perfect number.
28 is a perfect number.
496 is a perfect number.
8128 is a perfect number.
</pre>
===version 2===
<lang rexx>
/*REXX program to test if a number is perfect. */
 
arg low high .
if high=='' & low=='' then high=10000
if low=='' then low=1
if high=='' then high=low
w=length(high)
 
do j=low to high
if isperfect(j) then say right(j,w) 'is a perfect number.'
end
 
exit
 
 
/*─────────────────────────────────────ISPERFECT subroutine─────────────*/
isperfect: procedure; parse arg x /*get the number to be tested. */
if x=6 then return 1 /*handle this special case. */
if x//2==1 | x<28 then return 0 /*if odd or less then 28, nope. */
 
/*we know that perfect numbers */
/*can be expressed as: */
/* [2**n - 1] * [2** (n-1) ] */
 
do k=3 /*start at a power of three. */
?=(2**k-1)*2**(k-1) /*compute expression for a power.*/
if ?<x then iterate /*Too low? Then keep on truckin'*/
if ?>x then return 0 /*Too high? Number isn't perfect*/
if ?==x then leave /*this number is just right. */
end
 
sum=3+x%2 /*we know the following factors: */
/* 1 ('cause Mama said so.)*/
/* 2 (because it's even.) */
/* x/2 " " " */
 
do j=3 to x%2 /*starting at 3, find factors. */
if j*j>x then leave /*if past the sqrt of X, stop. */
if x//j==0 then do /*J divides X evenly, so ... */
sum=sum+j+x%j /*... add it and the other factor*/
end
end
 
return sum==x /*if the sum matches X, perfect! */
</lang>
Output (using the defaults):
<pre style="height:15ex;overflow:scroll">
6 is a perfect number.
28 is a perfect number.
496 is a perfect number.
8128 is a perfect number.
</pre>
 
=={{header|Ruby}}==