Anonymous user
Perfect numbers: Difference between revisions
m
→optimized using digital root: add/changed comments and whitespace.
m (→optimized using only even numbers: changed indentations for the ISPERFECT function.) |
m (→optimized using digital root: add/changed comments and whitespace.) |
||
Line 1,760:
===optimized using digital root===
This REXX version makes use of the fact that all ''known'' perfect numbers > 6 have a ''digital root'' of '''1'''.
<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==6 then return 1
/*[↓] perfect
do until y<10
parse var y r 2; do k=2 for length(y)-1;
y=r
end /*
if r\==1 then return 0
s=1
do j=2 while j*j<=x /*starting at 2, find the factors
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 /*
end /*j*/ /*(above) is marginally faster. */
return s==x
'''output''' is the same as the traditional version and is about '''5.3''' times faster (testing 34,000,000 numbers).
|