How to find Kaprekar numbers within a given range using Python?


A modified Kaprekar number is a positive whole number n with d digits, such that when we split its square into two pieces - a right hand piece r with d digits and a left hand piece l that contains the remaining d or d−1 digits, the sum of the pieces is equal to the original number (i.e. l + r = n).

You can find Kaprekar numbers within a given range by testing each number for the given condition in the given range. 

example

def print_Kaprekar_nums(start, end):
   for i in range(start, end + 1):
      # Get the digits from the square in a list:
      sqr = i ** 2
      digits = str(sqr)

      # Now loop from 1 to length of the number - 1, sum both sides and check
      length = len(digits)
      for x in range(1, length):
         left = int("".join(digits[:x]))
         right = int("".join(digits[x:]))
         if (left + right) == i:
            print("Number: " + str(i) + "Left: " + str(left) + " Right: " + str(right))

print_Kaprekar_nums(150, 8000)

Output

This will give the output −

Number: 297Left: 88 Right: 209
Number: 703Left: 494 Right: 209
Number: 999Left: 998 Right: 1
Number: 1000Left: 1000 Right: 0
Number: 2223Left: 494 Right: 1729
Number: 2728Left: 744 Right: 1984
Number: 4879Left: 238 Right: 4641
Number: 4950Left: 2450 Right: 2500
Number: 5050Left: 2550 Right: 2500
Number: 5292Left: 28 Right: 5264
Number: 7272Left: 5288 Right: 1984
Number: 7777Left: 6048 Right: 1729

Updated on: 05-Mar-2020

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements