Recurring Decimals
InterviewTime limit1sMemory limit128 MB
For each (a0, L), iterate the digit-rearrange-and-subtract map until a value repeats, then print the first repeated index j, the repeated value, and the cycle length.
- Level
Medium4 of 10
- Topics
- Hash map, Simulation, Implementation, Math
- Solved
- No attempts yet
Problem
The decimal representation of an integer can be turned into another integer by rearranging its digits. We use this to build a sequence.
You are given a non-negative integer and a digit count . From we obtain by the following rules.
- Write in decimal using exactly digits, adding leading zeros if necessary. For example, written with six digits, becomes .
- Rearrange the digits to form the largest possible integer and the smallest possible integer. In the example above, the largest is and the smallest is .
- Obtain by subtracting the smallest from the largest. In the example above, .
Repeating this computation gives a sequence .
For example, starting from with you get:
Because the number of digits is fixed, some value must eventually repeat, so there is always a pair with . In the example, works because .
Write a program that, given and , finds the smallest for which holds for some .
Input
The input consists of several datasets. Each dataset is a single line containing two integers and separated by a space, where and .
A line containing two zeros marks the end of the input and is not a dataset.
Output
For each dataset, find the smallest satisfying with , and print one line with the three integers , , and , separated by single spaces. Suppress leading zeros and do not print any extra characters.
You may assume that this is never greater than .