Kaprekar’s Constant – Python Challenge

In this challenge, we’re going to explore a fascinating mathematical curiosity known as Kaprekar’s Constant, and then write a Python program to demonstrate how it works.

Kaprekar’s constant, number 6174 has an odd particularity: If you rearrange its four digits in descending order (7641) and take away the number made of these same 4 digits in ascending order (1467) you will fall back on the initial number 7641 – 1467 = 6174!

But that’s not all… The Indian mathematician D. R. Kaprekar discovered something amazing about 4-digit numbers. Here’s the process he found:

  1. Take any 4-digit number (at least two different digits).
    Example: 3524

  2. Rearrange its digits to create:
    • The largest possible number: 5432
    • The smallest possible number: 2345
  3. Subtract the smaller number from the larger one:
    5432 – 2345 = 3087

  4. Now take this result and repeat the process!
    Step 1: 5432 – 2345 = 3087
    Step 2: 8730 – 0378 = 8352
    Step 3: 8532 – 2358 = 6174
    Step 4: 7641 – 1467 = 6174

Once you reach 6174, the process stops — because you’ll keep getting 6174 forever!

This number, 6174, is known as Kaprekar’s Constant. No matter which 4-digit number you start with (as long as the digits aren’t all identical), you will always end up at 6174 after a few iterations!

Let’s visualise this with 2025 as our starting 4-digit number:

Python Challenge

The initial challenge is to write a Python program that:

  • Asks the user to enter a 4-digit number (with at least two different digits).
  • Applies Kaprekar’s routine (rearrange digits, subtract, repeat).
  • Displays each step of the process.
  • Stops once it reaches 6174.
  • Outputs how many iterations it took to reach the constant.

Example output:

Enter a 4-digit number: 3524

Step 1: 5432 - 2345 = 3087
Step 2: 8730 - 0378 = 8352
Step 3: 8532 - 2358 = 6174

It took 3 iterations to reach Kaprekar's constant (6174).

Python Code (Solution)

Extra Challenge

Write a program to count how many iterations it takes for every 4-digit number (from 0001 to 9998) to reach 6174. Use this program to find out which numbers take the most iterations!

Warning: Make sure to remove any number with the same 4 digits (1111, 2222, 3333… as these cannot lead to Kaprekar’s constant: When applying the process described above on such a 4-digit number, the computer will loop indefinitely without reaching Kaprekar’s constant.

Did you like this challenge?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!