Recurring Decimals

Interview

Time limit1sMemory limit128 MB

Summary
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 a0a_0 and a digit count LL. From aia_i we obtain ai+1a_{i+1} by the following rules.

  1. Write aia_i in decimal using exactly LL digits, adding leading zeros if necessary. For example, written with six digits, 20122012 becomes 002012002012.
  2. Rearrange the digits to form the largest possible integer and the smallest possible integer. In the example above, the largest is 221000221000 and the smallest is 000122=122000122 = 122.
  3. Obtain ai+1a_{i+1} by subtracting the smallest from the largest. In the example above, 221000−122=220878221000 - 122 = 220878.

Repeating this computation gives a sequence a0,a1,a2,…a_0, a_1, a_2, \dots.

For example, starting from 8326883268 with L=6L = 6 you get:

  • a0=083268a_0 = 083268
  • a1=886320−023688=862632a_1 = 886320 - 023688 = 862632
  • a2=866322−223668=642654a_2 = 866322 - 223668 = 642654
  • a3=665442−244566=420876a_3 = 665442 - 244566 = 420876
  • a4=876420−024678=851742a_4 = 876420 - 024678 = 851742
  • a5=875421−124578=750843a_5 = 875421 - 124578 = 750843
  • a6=875430−034578=840852a_6 = 875430 - 034578 = 840852
  • a7=885420−024588=860832a_7 = 885420 - 024588 = 860832
  • a8=886320−023688=862632a_8 = 886320 - 023688 = 862632
  • …\dots

Because the number of digits is fixed, some value must eventually repeat, so there is always a pair i>ji > j with ai=aja_i = a_j. In the example, (i=8,j=1)(i = 8, j = 1) works because a8=a1=862632a_8 = a_1 = 862632.

Write a program that, given a0a_0 and LL, finds the smallest ii for which ai=aja_i = a_j holds for some j<ij < i.

Input

The input consists of several datasets. Each dataset is a single line containing two integers a0a_0 and LL separated by a space, where 1≤L≤61 \le L \le 6 and 0≤a0<10L0 \le a_0 < 10^L.

A line containing two zeros marks the end of the input and is not a dataset.

Output

For each dataset, find the smallest ii satisfying ai=aja_i = a_j with i>ji > j, and print one line with the three integers jj, aia_i, and i−ji - j, separated by single spaces. Suppress leading zeros and do not print any extra characters.

You may assume that this ii is never greater than 2020.

Examples1

  1. Example 1

    Input
    2012 4
    83268 6
    1112 4
    0 1
    99 2
    0 0
    
    Expected output
    3 6174 1
    1 862632 7
    5 6174 1
    0 0 1
    1 0 1