Jump to content

Kaprekar numbers: Difference between revisions

→‎{{header|D}}: no need to remove a valid approach with a C translation
(Improved second D version)
(→‎{{header|D}}: no need to remove a valid approach with a C translation)
Line 174:
<pre>[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
54</pre>
===Lower level version===
 
MoreAlternative thanversion, tenright timesto fasterleft, produces (same output):
<lang d>import std.stdio, std.algorithm, std.range;
 
pure nothrow<lang d>bool isKaprekar(in long n) {
ulong a = n * n, b = a % 10;
in {
assertfor (nulong >d 0= 1, "isKaprekar(n)t is= defined0; for na > 0."); d *= 10) {
b += t * return trued;
assert(n <= 3_162_277_660UL, "isKaprekar(n) overflow.");
a /= 10;
} body {
immutable ulong nn = nif *(b && a + b == n;)
ulong tens = return 1;
while (tens < nn) t = a % 10;
tens *= 10;}
return n == 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
Cookies help us deliver our services. By using our services, you agree to our use of cookies.