Numerology

Time limit2sMemory limit128 MB

Summary
For each (n, p), find the smallest base 2 to 10^6 where the digits of n form a pattern repetition and print the digit sequence.
Level

Medium7 of 10

Topics
Brute force, Implementation, Math
Solved
No attempts yet

Problem

In many cultures certain numbers carry particular meanings. For example, 666 is often linked with the Devil, and 777 with good luck. Numbers like these tend to form a visual pattern, so a numerologist hunting for the next meaningful number cares about spotting such patterns.

A number only reveals an interesting pattern in the right base. For instance, 666 in hexadecimal is 29a, far less striking than its base-10 form. To account for every base that past (or even alien!) cultures might have used, you want to test whether a number matches a pattern of interest when written in some base.

We write a number converted to base bb as a sequence of symbols S=⟨s1,s2,…,sL⟩S = \langle s_1, s_2, \dots, s_L \rangle, where each symbol is an integer (its digit value in that base), listed most significant digit first. For example, the decimal number 10 written in base 2 is 10101010, giving S=⟨1,0,1,0⟩S = \langle 1, 0, 1, 0 \rangle and L=4L = 4.

A pattern is a string, for example ab. A sequence SS matches a pattern pp if and only if both of the following hold:

  1. LL is at least the length of pp.
  2. There is a one-to-one correspondence between the distinct characters of pp and the distinct symbols of SS such that, when pp is repeatedly concatenated with itself and then truncated to a string rr of length LL, replacing every character of rr by its mapped symbol yields exactly SS.

Under this definition, 10 in base 2 matches the pattern ab (map a→\to1 and b→\to0, so abab becomes ⟨1,0,1,0⟩\langle 1, 0, 1, 0 \rangle).

Input

The first line contains the number of data sets KK. Each of the following KK lines contains a positive integer nn and a string pp: the number you care about and the pattern to match against. nn fits in a 64-bit integer, pp has at most 10 characters, and every character of pp is a lowercase letter from a to j.

Output

For each data set output Data Set x: on its own line, where xx is the data set's number starting from 1. Then output the smallest base bb with 2≤b≤10000002 \le b \le 1000000 such that nn written in base bb matches the pattern pp. On the next line output the integer symbols of that matching sequence, separated by single spaces with no trailing space. If no base in the range produces a match, output No such base. instead of the base and the sequence. Separate consecutive data sets with a blank line.

Examples1

  1. Example 1

    Input
    4
    5 ab
    777 a
    3735928559 deadbeef
    349485 abcdefghij
    
    Expected output
    Data Set 1:
    2
    1 0 1
    
    Data Set 2:
    6
    3 3 3 3
    
    Data Set 3:
    16
    13 14 10 13 11 14 14 15
    
    Data Set 4:
    No such base.