Kaprekar numbers: Difference between revisions

Added third version, as suggested.
(→‎{{header|D}}: no need to remove a valid approach with a C translation)
(Added third version, as suggested.)
Line 187:
}
return 0;
}</lang>
This third version, from the C version, is more than ten times faster than the first version (same output):
 
<lang d>import std.stdio, std.algorithm, std.range;
pure nothrow bool isKaprekar(in long n)
in {
assert(n > 0, "isKaprekar(n) is defined for n > 0.");
assert(n <= 3_162_277_660UL, "isKaprekar(n) overflow.");
} body {
immutable ulong nn = n * n;
ulong tens = 1;
while (tens < nn)
tens *= 10;
while ((tens /= 10) > n)
if (nn - n == (nn / tens) * (tens - 1))
return true;
return n == 1;
}
void main() {
writeln(filter!isKaprekar(iota(1, 10_000)));
writeln(count!isKaprekar(iota(1, 1_000_000)));
}</lang>
 
Anonymous user