Perfect numbers: Difference between revisions
Content added Content deleted
(Added Quackery.) |
(→{{header|AppleScript}}: Added two idiomatic solutions.) |
||
Line 549: | Line 549: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
===Functional=== |
|||
{{Trans|JavaScript}} |
{{Trans|JavaScript}} |
||
<lang AppleScript>-- PERFECT NUMBERS ----------------------------------------------------------- |
<lang AppleScript>-- PERFECT NUMBERS ----------------------------------------------------------- |
||
Line 661: | Line 661: | ||
{{Out}} |
{{Out}} |
||
<lang AppleScript>{6, 28, 496, 8128}</lang> |
<lang AppleScript>{6, 28, 496, 8128}</lang> |
||
---- |
|||
===Idiomatic=== |
|||
<lang applescript>on isPerfect(n) |
|||
-- Joining the dots in the Wikipedia entry suggests that all perfect numbers |
|||
-- identifiable by AppleScript end with either 6 or 8. Testing for this |
|||
-- immediately eliminates negatives, fractional numbers, and 4/5 of what's left. |
|||
tell (n mod 10) to if not ((it = 6) or (it = 8)) then return false |
|||
set sum to 1 |
|||
set sqrt to n ^ 0.5 |
|||
set limit to sqrt div 1 |
|||
if (limit = sqrt) then |
|||
set sum to sum + limit |
|||
set limit to limit - 1 |
|||
end if |
|||
repeat with i from 2 to limit |
|||
if (n mod i is 0) then |
|||
set sum to sum + i + n div i |
|||
if (sum > n) then exit repeat |
|||
end if |
|||
end repeat |
|||
return (sum = n) |
|||
end isPerfect |
|||
local output, n |
|||
set output to {} |
|||
repeat with n from 1 to 100000 |
|||
if (isPerfect(n)) then set end of output to n |
|||
end repeat |
|||
return output</lang> |
|||
{{output}} |
|||
<lang applescript>{6, 28, 496, 8128}</lang> |
|||
But for practical purposes, since only the first 7 of the known perfect numbers can be accurately represented by AppleScript numbers, a simple look-up table would be the best approach: |
|||
<lang applescript>on isPerfect(n) |
|||
tell (n mod 10) to if not ((it = 6) or (it = 8)) then return false |
|||
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 |
|||
local output, n |
|||
set output to {} |
|||
repeat with n from 2 to 33551000 by 2 |
|||
if (isPerfect(n) is true) then set end of output to n |
|||
end repeat |
|||
return output</lang> |
|||
{{output}} |
|||
<lang applescript>{6, 28, 496, 8128, 33550336}</lang> |
|||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |