Multi-base happy numbers

For each set of bases, find the smallest integer above 1 whose repeated digit-square iteration reaches 1 in every listed base.

Medium6MathSimulationHash mapNo attempts yetTime limit5sMemory limit512 MB

Problem

Take an integer NN and replace it by the sum of the squares of its digits. A number is happy when repeating this step eventually produces 1. Starting from 82, for example:

8*8 + 2*2       = 64 + 4    = 68
6*6 + 8*8       = 36 + 64   = 100
1*1 + 0*0 + 0*0 = 1 + 0 + 0 = 1

The process reached 1, so 82 is happy.

The same number can be happy in one base and not happy in another. The base 10 number 82 is written 10001 in base 3, and in base 3 the process never reaches 1.

Happiness in base bb is defined this way. Write the number in base bb and add up the squares of its digits to get a new number. Repeat. If 1 ever comes out, the number is happy in base bb.

Given a list of bases, find the smallest integer greater than 1 that is happy in every one of those bases.

Input

The first line contains the number of test cases TT. Each of the next TT lines holds one test case: a space separated list of distinct bases in increasing order.

Limits

  • every base bb in the input satisfies 2b102 \le b \le 10
  • 1T5001 \le T \le 500
  • each test case lists at least 2 and at most 9 bases

Output

For each test case print one line in this format.

Case #X: K

XX is the test case number starting from 1, and KK is the decimal form of the smallest integer greater than 1 that is happy in all of the given bases.