Perfect numbers: Difference between revisions
Content deleted Content added
m Phix/mpfr |
→Version 2: Now uses Wren-math module. |
||
Line 3,243: | Line 3,243: | ||
===Version 2=== |
===Version 2=== |
||
{{libheader|Wren-math}} |
|||
This makes use of the fact that all known perfect numbers are of the form <big> (2<sup>''n''</sup> - 1) × 2<sup>''n'' - 1</sup></big> where <big> (2<sup>''n''</sup> - 1)</big> is prime and finds the first seven perfect numbers instantly. The numbers are too big after that to be represented accurately by Wren. |
This makes use of the fact that all known perfect numbers are of the form <big> (2<sup>''n''</sup> - 1) × 2<sup>''n'' - 1</sup></big> where <big> (2<sup>''n''</sup> - 1)</big> is prime and finds the first seven perfect numbers instantly. The numbers are too big after that to be represented accurately by Wren. |
||
<lang ecmascript> |
<lang ecmascript>import "/math" for Int |
||
if (n < 2 || !n.isInteger) return false |
|||
if (n%2 == 0) return n == 2 |
|||
if (n%3 == 0) return n == 3 |
|||
var d = 5 |
|||
while (d*d <= n) { |
|||
if (n%d == 0) return false |
|||
d = d + 2 |
|||
if (n%d == 0) return false |
|||
d = d + 4 |
|||
} |
|||
return true |
|||
} |
|||
var isPerfect = Fn.new { |n| |
var isPerfect = Fn.new { |n| |
||
Line 3,276: | Line 3,265: | ||
while (count < 7) { |
while (count < 7) { |
||
var n = 2.pow(p) - 1 |
var n = 2.pow(p) - 1 |
||
if ( |
if (Int.isPrime(n)) { |
||
n = n * 2.pow(p-1) |
n = n * 2.pow(p-1) |
||
if (isPerfect.call(n)) { |
if (isPerfect.call(n)) { |