than three or four (in base 10), the routine may terminate at one of several fixed points or may enter one of several cycles instead, depending on the starting value of the sequence. See the table in the section above for base 10 fixed points and cycles. The number of cycles increases rapidly with larger digit lengths, and all but a small handful of these cycles are of length three. For example, for 20-digit numbers in base 10, there are fourteen constants (cycles of length one) and ninety-six cycles of length greater than one, all but two of which are of length three. Odd digit lengths produce fewer different end results than even digit lengths. Programming example The example below implements the Kaprekar mapping described in the definition above to search for Kaprekar's constants and cycles in Python. Leading zeroes discarded def get_digits(x, b): digits = [] while x > 0: digits.append(x % b) x = x // b return digits def form_number(digits, b): result = 0 for i in range(0, len(digits)): result = result * b + digits[i] return result def kaprekar_map(x, b): descending = form_number(sorted(get_digits(x, b), reverse=True), b) ascending = form_number(sorted(get_digits(x, b)), b) return descending - ascending def kaprekar_cycle(x, b): x = int (str(x), b) seen = [] while x not in seen: seen.append(x) x = kaprekar_map(x, b) cycle = [] while x not in cycle: cycle.append(x) x = kaprekar_map(x, b) return cycle Leading zeroes retained def digit_count(x, b): count = 0 while x > 0: count = count + 1 x = x // b return count def get_digits(x, b, init_k): k = digit_count(x, b) digits = [] while x > 0: digits.append(x % b) x = x // b for i in range(k, init_k): digits.append(0) return digits def form_number(digits, b): result = 0 for i in range(0, len(digits)): result = result * b + digits[i] return result def kaprekar_map(x, b, init_k): descending = form_number(sorted(get_digits(x, b, init_k), reverse=True), b) ascending = form_number(sorted(get_digits(x, b, init_k)), b) return descending - ascending def kaprekar_cycle(x, b): x = int (str(x), b) init_k = digit_count(x, b) seen = [] while x not in seen: seen.append(x) x = kaprekar_map(x, b, init_k) cycle = [] while x not in cycle: cycle.append(x) x = kaprekar_map(x, b, init_k) return cycle See also Arithmetic dynamics Dudeney number Factorion Happy number Kaprekar number Meertens number Narcissistic number Perfect digit-to-digit invariant Perfect digital invariant Sum-product number Sorting algorithm Citations