Fractran

Time limit1sMemory limit128 MB

Summary
Given a list of fractions and a start value, repeatedly apply the first fraction that keeps the value an integer, and report the first m exponents of powers of two that appear.
Level

Medium7 of 10

Topics
Simulation, Math, Number theory, Implementation
Solved
No attempts yet

Problem

To play the "fraction game" for a given list of fractions f1,f2,…,fkf_1, f_2, \dots, f_k and a starting integer NN, repeatedly multiply the integer you currently hold (initially NN) by the earliest fif_i in the list for which the product is an integer. As soon as no such fif_i exists, the game stops.

Formally, define the sequence by S0=NS_0 = N and Sj+1=fiSjS_{j+1} = f_i S_j, where ii is the smallest index with 1≤i≤k1 \le i \le k such that fiSjf_i S_j is an integer while f1Sj,…,fi−1Sjf_1 S_j, \dots, f_{i-1} S_j are not.

For example, with the eight fractions f1=170/39f_1 = 170/39, f2=19/13f_2 = 19/13, f3=13/17f_3 = 13/17, f4=69/95f_4 = 69/95, f5=19/23f_5 = 19/23, f6=1/19f_6 = 1/19, f7=13/7f_7 = 13/7, f8=1/3f_8 = 1/3 and N=21N = 21, the game produces the finite sequence (21,39,170,130,190,138,114,6,2)(21, 39, 170, 130, 190, 138, 114, 6, 2). In general the sequence may be infinite.

Given a fraction list and a starting integer, we are interested only in the powers of 22 that appear in the sequence.

Input

The input contains several test cases. Each test case begins with three integers mm, NN, and kk, where 1≤m≤401 \le m \le 40, 1≤N≤10001 \le N \le 1000, and 1≤k≤1001 \le k \le 100. Then follow the kk fractions f1,…,fkf_1, \dots, f_k: for each fraction the numerator is given first, then the denominator. Both are positive integers less than 10001000 whose greatest common divisor is 11. The last test case is followed by a single 00.

Output

For each test case, output on one line the mm numbers e1,…,eme_1, \dots, e_m, separated by single spaces, such that 2e1,…,2em2^{e_1}, \dots, 2^{e_m} are the first mm powers of 22 that occur in the sequence. You may assume that at least mm powers of 22 occur among the first 76543217654321 elements of the sequence.

Examples5

  1. Example 1

    Input
    1 21 8 170 39 19 13 13 17 69 95 19 23 1 19 13 7 1 3
    20 2 14 17 91 78 85 19 51 23 38 29 33 77 29 95 23 77 19 1 17 11 13 13 11 15 2 1 7 55 1
    0
    
    Expected output
    1
    1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67
    
  2. Example 2

    Input
    5 1 1 2 1
    0
    
    Expected output
    0 1 2 3 4
    
  3. Example 3

    Input
    3 8 1 2 1
    0
    
    Expected output
    3 4 5
    
  4. Example 4

    Input
    6 2 2 4 3 3 2
    0
    
    Expected output
    1 2 3 4 5 6
    
  5. Example 5

    Input
    4 8 1 1 2
    0
    
    Expected output
    3 2 1 0