Activity #4: Kaprekar's Constant β individual
6174 is known as Kaprekar's Constant (https://en.wikipedia.org/wiki/6174 (number)) after the Indian mathematician D. R. Kaprekar. This number can be obtained using Kaprekar's routine:
1. Take any four-digit number that has at least two different digits (add leading zeros to numbers with fewer than four digits)
2. Sort the digits in descending and then in ascending order to get two four-digit numbers, adding leading zeros if necessary
3. Subtract the smaller number from the bigger number to get a new four-digit number
4. Go back to step 2 and repeat
Kaprekar's routine will always reach its fixed point, 6174, in at most 8 iterations. Once 6174 is reached, the process will continue to yield 7641 β 1467 = 6174.
For example, choose 3524:
5432 β 2345 = 3087
8730 β 0378 = 8352
8532 β 2358 = 6174
For example, choose 137 (add a leading zero):
7310 β 0137 = 7173
7731 β 1377 = 6354
6543 β 3456 = 3087
8730 β 0378 = 8352
8532 β 2358 = 6174
The only four-digit numbers for which Kaprekar's routine does not reach 6174 are repdigits (numbers where all digits are the same, such as 1111) which give 0000 after a single iteration. All other four-digit numbers eventually reach 6174, as long as leading zeros are used to keep the number of digits at four.
Attach the assignment to your HW/Lab
Date:
You name
ENGR 102 Section Lab 7b
DUE DATE: 10/10/2022
Team # (table)
Write a program named kaprekars_constant.py that takes in an integer from the user between 0 and 9999 and implements Kaprekar's routine. Have your program output the sequence of numbers to reach 6174 and the number of iterations to get there. Format your output as shown below.
Example output (using input 2026):
Enter a four-digit integer: 2026
2026 > 5994 > 5355 > 1998 > 8082 > 8532 > 6174
2026 reaches 6174 via Kaprekar's routine in 6 iterations
Hints:
β’ Consider converting numbers to strings for sorting, and back to numbers for calculating
β’ Pad the number with 0s when it has fewer than four digits (remember string concatenation?)
β’ The list(), <listname>.sort(), and <string>.join() methods may be helpful