bool isKaprekar(in long n) pure nothrow
in {
    assert(n > 0, "isKaprekar(n): n must be > 0");
    assert(n <= uint.max, "isKaprekar(n): n must be <= uint.max");
} body {
    ulong powr = n ^^ 2UL;
    ulong tens = 10, r, l;
    while (r < n) {
        r = powr % tens;
        l = powr / tens;
        if (r && l + r == n)
            return true;
        tens *= 10;
    }
    return false;
}

--

A positive integer is a Kaprekar number if:

-It is 1
-The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive.

Example: 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.

See also http://rosettacode.org/wiki/Kaprekar_numbers

Reply via email to