Kaprekar numbers

Revision as of 06:48, 7 June 2011 by rosettacode>Paddy3118 (New task and Python solution.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

A positive integer is a Kaprekar number if the string representation of its square can be split once into parts that when summed add up to the original number.

Kaprekar numbers is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

For example 2223 is a Kaprekar number as 2223*2223 == 4941729 and 494 + 1729 == 2223

The series of kaprekar numbers begins: 1, 9, 45, 55, ....

The task is to generate and show all the Kaprekar numbers less than 10,000

As a stretch goal count and show how many Kaprekar numbers their are that are less than one million.

Note: In comparing splits of the square, a split of all zeroes is not counted - as zero is not considered positive. However a conceptual single split at the very end or before the first digit that produces one empty string does have the empty string counted.

Python

(Swap the commented return statements to return the split information). <lang python>>>> def k(n): if n <1: return None elif n == 1: return n #return (1, ("1", "")) else: n2 = str(n**2) for i in range(1,len(n2)): a, b = int(n2[:i]), int(n2[i:]) if a and b and a + b == n: return n #return (n, (n2[:i], n2[i:]))


>>> [x for x in range(10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1000000) if k(x)]) 54 >>> </lang>