How do you get to Keprekar's constant when you start with a one digit number?

4 visualizzazioni (ultimi 30 giorni)
How do you get to Keprekar's constant when you start with a one digit number? As far as l know there are 2 values considered as Keprekar's constants 495 (if you start with a 3 digit number) or 6174 if you start with a 4 digit number. I am working on a function to count how many steps are needed to take a number and get it to Keprekars constant using Keprekar's routine described below. I saw a Matlab cody challenge linked here( https://www.mathworks.com/matlabcentral/cody/groups/2/problems/68 ) where one of the test cases says you actually can get to Keprekars constant when you start with one digit.
Keprekar's Routine:
  1. Take any four-digit number, using at least two different digits (leading zeros are allowed).
  2. Arrange 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.
  4. Go back to step 2 and repeat
Source for Keprekars Routine Description:

Risposta accettata

Walter Roberson
Walter Roberson il 26 Mag 2021
new = randi(9)
new = 3
while true
old = new
new = sprintf('%04d', old)
new = str2num(sort(new, 'descend')) - str2num(sort(new,'ascend'))
if new == old; break; end
end
old = 3
new = '0003'
new = 2997
old = 2997
new = '2997'
new = 7173
old = 7173
new = '7173'
new = 6354
old = 6354
new = '6354'
new = 3087
old = 3087
new = '3087'
new = 8352
old = 8352
new = '8352'
new = 6174
old = 6174
new = '6174'
new = 6174
new
new = 6174
  2 Commenti
Ntandoyakhe Tshuma
Ntandoyakhe Tshuma il 26 Mag 2021
Oh I see. I thought about adding zeros to it but my concern was that in the case of x being 1 it would eventually just get to zero.
x = 1
asc = 0001
dsc = 1000
dsc - asc = 999
dsc = 999
asc =999
dsc - asc = 0
but with the way your code is formatted the value would be 0999 allowing the code to keep running. Thank you.
Walter Roberson
Walter Roberson il 26 Mag 2021
Note: the code could be written more efficiently. The point was not to be as efficient as possibe: the point was to show it could be done.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su MATLAB Report Generator in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by