Home‎ > ‎ProgComp‎ > ‎ProgComp 2015‎ > ‎

Task 0 - Junior - Kaprekar Numbers

Junior Task. Kaprekar Numbers

Available Marks: 7

This stern looking gentleman is Mr D R Kaprekar (1905–1986), an Indian schoolteacher and recreational mathematician. Among his many achievements is the discovery of a set of numbers with interesting properties that now bear his name.

Consider a positive integer k with n digits. Follow these steps:

  1. Square k.
  2. Split the result into two pieces, the last n digits and the rest.
  3. Add these pieces (if one is empty, treat as zero).
  4. If the sum is equal to k, then k is a Kaprekar number, otherwise it's not.

Example

1 and 45 are both Kaprekar numbers because

1*1 = 1 and 0 + 1 = 1
45*45 = 2025 and 20 + 25 = 45
but 123 is not since
123*123 = 15129 and 15 + 129 is not equal to 123

Your task

Write a program that displays all the Kaprekar numbers less than 10000, on one line. A god solution is to write a function that tests an integer to see if it's a Kaprekar number, then use it in a loop that tries all possibilities. If your programming language doesn't support mixing integers and strings, you may need to use a built-in function to convert the number to a string so you can pick off the last n digits. Alternatively you can use modular arithmetic (% or Mod operator).

If you've just started programming, for partial marks just write a program that reads a number, determines if it's a Kaprekar number or not, and displays a suitable message that includes the number. Test it, one at a time, with each of these numbers

45 673 272 2223 7381 7777 9998

Remember, only paste unedited output from your program.


Reference: Wolfram Mathworld. Image source: Wikimedia

Comments