Perfect numbers: Difference between revisions
Content added Content deleted
No edit summary |
(→{{header|AppleScript}}: →Idiomatic: Tidied. Added Euclid method.) |
||
Line 718:
----
===Idiomatic===
====Sum of proper divisors====
<lang applescript>on isPerfect(n)▼
<lang applescript>on aliquotSum(n)
set sum to 1
set sqrt to n ^ 0.5
Line 731 ⟶ 729:
end if
repeat with i from 2 to limit
if (n mod i is 0) then set sum to sum + i + n div i
set sum to sum + i + n div i▼
▲ if (sum > n) then exit repeat
end if▼
end repeat
return
end aliquotSum
on isPerfect(n)
if (n > 1.37438691328E+11) then return missing value -- Too high for perfection to be determinable.▼
-- All the known perfect numbers listed in Wikipedia end with either 6 or 28.
-- These endings are either preceded by odd digits or are the numbers themselves.
tell (n mod 10) to ¬
return ((((it = 6) and ((n mod 20 = 16) or (n = 6))) or ¬
((it = 8) and ((n mod 200 = 128) or (n = 28)))) and ¬
(my aliquotSum(n) = n))
end isPerfect
local output, n
set output to {}
repeat with n from 1 to
if (isPerfect(n)) then set end of output to n
end repeat
Line 750 ⟶ 755:
<lang applescript>{6, 28, 496, 8128}</lang>
====Euclid====
<lang applescript>on isPerfect(n)
-- All the known perfect numbers listed in Wikipedia end with either 6 or 28.
-- These endings are either preceded by odd digits or are the numbers themselves.
▲ if (n > 1.37438691328E+11) then return missing value -- Too high for perfection to be determinable.
tell (n mod 10) to ¬
return (n is in {6, 28, 496, 8128, 33550336, 8.589869056E+9, 1.37438691328E+11})▼
if not (((it = 6) and ((n mod 20 = 16) or (n = 6))) or ((it = 8) and ((n mod 200 = 128) or (n = 28)))) then ¬
return false
-- Work through the only seven primes p where (2 ^ p - 1) is also prime
-- and (2 ^ p - 1) * (2 ^ (p - 1)) is a number that AppleScript can handle.
repeat with p in {2, 3, 5, 7, 13, 17, 19}
tell (2 ^ p - 1) * (2 ^ (p - 1))
if (it < n) then
else
▲ end if
end tell
end repeat
return missing value
end isPerfect
Line 761 ⟶ 778:
set output to {}
repeat with n from 2 to 33551000 by 2
if (isPerfect(n)
end repeat
return output</lang>
Line 767 ⟶ 784:
{{output}}
<lang applescript>{6, 28, 496, 8128, 33550336}</lang>
====Practical====
But since AppleScript can only physically manage seven of the known perfect numbers, they may as well be in a look-up list for maximum efficiency:
▲<lang applescript>on isPerfect(n)
if (n > 1.37438691328E+11) then return missing value -- Too high for perfection to be determinable.
▲ return (n is in {6, 28, 496, 8128, 33550336, 8.589869056E+9, 1.37438691328E+11})
end isPerfect</lang>
=={{header|ARM Assembly}}==
|