Problem 68. Kaprekar Steps
6174 is the Kaprekar constant. All natural numbers less than 10,000 (except some with same digits) can be reduced to 6174 in the following steps:
Order the digits of the number in descending and ascending order and compute the difference. Repeat the process till you get 6174.
Example
n = 2376
Digits in descending order = 7632
Digits in ascending order = 2367
Step1:
>> 7632 - 2367
ans = 5265
Step 2:
>> 6552 - 2556
ans = 3996
Step3:
>> 9963 - 3699
ans = 6264
Step4
>> 6642 - 2466
ans = 4176
Step5
>> 7641 - 1467
ans = 6174
Total number of steps = 5.
Your function should return the number of Kaprekar steps for a given input. Numbers such as 2222 will end in zero. These numbers will never result in 6174. They should return Inf.
Solution Stats
Problem Comments
-
18 Comments
Show
15 older comments
Aryeh S
on 30 Nov 2022
ATTENTION
This problem statement is poorly given and leaves out a crucial element- the input number must always have 4 digits, so if 1 is the input, the first iteration should be 1000-0001. the second iteration should be 9990-0999. for the problem as stated, the test suite gives solutions that are incorrect.
Peter
on 18 Aug 2023
Quite interesting!
Niccolò
on 2 Nov 2023
interesting problem
Solution Comments
Show commentsProblem Recent Solvers2332
Suggested Problems
-
Back to basics 23 - Triangular matrix
1031 Solvers
-
Find best placement for ordered dominoes (harder)
312 Solvers
-
Find the largest value in the 3D matrix
1546 Solvers
-
708 Solvers
-
Side of an equilateral triangle
6355 Solvers
More from this Author96
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!