Perfect numbers: Difference between revisions
Content added Content deleted
(Updated first D entry) |
(Updated both D entries) |
||
Line 458: | Line 458: | ||
=={{header|D}}== |
=={{header|D}}== |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
return n == iota(1, n - 1).filter!(i => n % i == 0).sum; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
{{out}} |
|||
<pre>[6, 28, 496, 8128]</pre> |
|||
===Faster Imperative Version=== |
===Faster Imperative Version=== |
||
{{trans|Algol}} |
{{trans|Algol}} |
||
<lang d>import std.stdio, std.math, std.range, std.algorithm; |
<lang d>import std.stdio, std.math, std.range, std.algorithm; |
||
bool |
bool isPerfectNumber2(in int n) pure nothrow { |
||
if (n < 2) |
if (n < 2) |
||
return false; |
return false; |
||
int |
int total = 1; |
||
foreach (immutable i; 2 .. cast(int)real(n).sqrt + 1) |
foreach (immutable i; 2 .. cast(int)real(n).sqrt + 1) |
||
if (n % i == 0) { |
if (n % i == 0) { |
||
immutable int q = n / i; |
immutable int q = n / i; |
||
total += i; |
|||
if (q > i) |
if (q > i) |
||
total += q; |
|||
} |
} |
||
return |
return total == n; |
||
} |
} |
||
void main() { |
void main() { |
||
10_000.iota.filter! |
10_000.iota.filter!isPerfectNumber2.writeln; |
||
}</lang> |
}</lang> |
||
{{out}} |
{{out}} |
||
Line 485: | Line 501: | ||
With a <code>33_550_337.iota</code> it outputs: |
With a <code>33_550_337.iota</code> it outputs: |
||
<pre>[6, 28, 496, 8128, 33550336]</pre> |
<pre>[6, 28, 496, 8128, 33550336]</pre> |
||
⚫ | |||
Same output. |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
return n == reduce!((s, i) => n % i ? s : s + i)(0, iota(1, n-1)); |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|E}}== |
=={{header|E}}== |