Coding challenge

Take any 4-digit number where not all digits are equal (for instance, $3524$). Arrange the digits in descending order ($5432$) and ascending order ($2345$). Subtract the smaller from the larger: $5432 - 2345 = 3087$. Now repeat this exact process with $3087$.

In 1949, Indian mathematician D.R. Kaprekar discovered that within at most 7 steps, you will always reach the number 6174, which then repeats forever ($7641 - 1467 = 6174$).

Built-in helper functions: To help you with sorting the digits, we have provided two built-in functions:

  • sort_digits_desc(n) — sorts digits in descending order (e.g. $3524 \to 5432$).
  • sort_digits_asc(n) — sorts digits in ascending order (e.g. $3524 \to 2345$).

Write a loop that carries out this routine for your favorite 4-digit number (e.g. $n = 3524$). How many steps does it take to reach 6174?

Type your code here:


Lua reference

See your results here: