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}}==
===Functional Version===
<lang d>import std.stdio, std.algorithm, std.range;

bool isPerfectNumber1(in uint n) pure nothrow
in {
assert(n > 0);
} body {
return n == iota(1, n - 1).filter!(i => n % i == 0).sum;
}

void main() {
iota(1, 10_000).filter!isPerfectNumber1.writeln;
}</lang>
{{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 isPerfectNumber(in int n) pure nothrow {
bool isPerfectNumber2(in int n) pure nothrow {
if (n < 2)
if (n < 2)
return false;
return false;


int sum = 1;
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;
sum += i;
total += i;
if (q > i)
if (q > i)
sum += q;
total += q;
}
}


return sum == n;
return total == n;
}
}


void main() {
void main() {
10_000.iota.filter!isPerfectNumber.writeln;
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>

===Functional Style===
Same output.
<lang d>import std.stdio, std.algorithm, std.range;

bool isPerfect(in uint n) pure nothrow
in {
assert(n > 0);
} body {
return n == reduce!((s, i) => n % i ? s : s + i)(0, iota(1, n-1));
}

void main() {
iota(1, 10_000).filter!isPerfect.writeln;
}</lang>


=={{header|E}}==
=={{header|E}}==