Anonymous user
Perfect numbers: Difference between revisions
m
→traditional method: added/changed comments and whitespace.
m (→Lucas-Lehmer + other optimizations: add/changed comments and whitespace.) |
m (→traditional method: added/changed comments and whitespace.) |
||
Line 1,718:
:::* a ''corresponding factor'' is used when a factor is found
:::* testing is stopped if the sum of the factors exceeds '''X'''
<lang rexx>/*REXX program tests if a number (or a range of numbers) is/are perfect. */
parse arg low high . /*obtain the specified number(s). */
if high=='' & low=='' then high=34000000 /*if no
if low=='' then low=1 /*if no LOW, then assume unity. */
if high=='' then high=low /*if no HIGH, then assume LOW. */
w=length(high) /*use W for formatting the output. */
numeric digits max(9,w+2) /*ensure enough digits to handle
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPerfect: procedure; parse arg x 1 y /*
if x
do until y<10
parse var y r 2;
y=r
end /*until*/
end /*j*/ /*(above) is marginally faster. */▼
s=1 /*the first factor of X. ___*/
do j=2 while j*j<=x /*starting at 2, find the factors ≤√ X */
if x//j\==0 then iterate /*J isn't a factor of X, so skip it. */
s = s + j + x%j /*··· add it and the other factor. */
if s>x then return 0 /*Is the sum too big? It ain't perfect*/
▲ end /*j*/ /*(above) is marginally faster. */
return s==x /*if the sum matches X, it's perfect! *//</lang>
'''output''' when using the default inputs:
6 is a perfect number.
|