Jump to content

Perfect numbers: Difference between revisions

Updated both D entries
(Updated first D entry)
(Updated both D entries)
Line 458:
 
=={{header|D}}==
===Functional StyleVersion===
<lang d>import std.stdio, std.algorithm, std.range;
 
bool isPerfectisPerfectNumber1(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!isPerfectisPerfectNumber1.writeln;
}</lang>
{{out}}
<pre>[6, 28, 496, 8128]</pre>
 
===Faster Imperative Version===
{{trans|Algol}}
<lang d>import std.stdio, std.math, std.range, std.algorithm;
 
bool isPerfectNumberisPerfectNumber2(in int n) pure nothrow {
if (n < 2)
return false;
 
int sumtotal = 1;
foreach (immutable i; 2 .. cast(int)real(n).sqrt + 1)
if (n % i == 0) {
immutable int q = n / i;
sumtotal += i;
if (q > i)
sumtotal += q;
}
 
return sumtotal == n;
}
 
void main() {
10_000.iota.filter!isPerfectNumberisPerfectNumber2.writeln;
}</lang>
{{out}}
Line 485 ⟶ 501:
With a <code>33_550_337.iota</code> it outputs:
<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}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.