302. Python Program to Count the Steps of Kaprekar's Routine
HardPhase 3 · Challenge
There are a few steps, but you know every tool: a while loop, a list with sort(), and text you build one character at a time. Try the number 3524 on paper first.
Overview
In 1949 the Indian maths teacher D. R. Kaprekar found a surprise: almost every 4-digit number reaches 6174 with the same few steps, and then stays there. It is a fun puzzle about digits and loops.
Problem Statement
Rashid heard about the magic number 6174 and wants to test it. Read a 4-digit number. Then repeat this step until the number is 6174:
- Put the 4 digits in order from the biggest to the smallest. This is the big number.
- Put the same digits in order from the smallest to the biggest. This is the small number.
- Take the small number away from the big number. The result is the new number.
Always keep 4 digits. If a result has fewer, put zeros in front: 999 is written 0999. The small number can start with zeros too, like 0378.
Print each step on its own line in the format 5432 - 2345 = 3087, all with 4 digits. At the end, print the number of steps in the format Steps: 3. If the input is already 6174, there are no steps: print only Steps: 0.
Examples
Example 1. Input 3524 gives:
5432 - 2345 = 3087
8730 - 0378 = 8352
8532 - 2358 = 6174
Steps: 3
Why: the digits of 3524 give 5432 and 2345, and the difference is 3087. Two more steps reach 6174, so the count is 3.
Example 2. Input 2111 gives:
2111 - 1112 = 0999
9990 - 0999 = 8991
9981 - 1899 = 8082
8820 - 0288 = 8532
8532 - 2358 = 6174
Steps: 5
Why: 2111 minus 1112 is 999, written 0999. Its digits are 0, 9, 9 and 9, so the next step is 9990 minus 0999.
Input
One whole number from 1000 to 9999. Its digits are not all the same, so the routine always reaches 6174. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line for each step, then the Steps: line. The tests try 8 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.