#TENKA12017F. ModularPowerEquation!!

ModularPowerEquation!!

Score : 14001400 points

Problem Statement

Process the QQ queries below.

  • You are given two integers AiA_i and MiM_i. Determine whether there exists a positive integer KiK_i not exceeding 2×10182 \times 10^{18} such that AiKiKiA_i^{K_i} ≡ K_i (mod(mod Mi)M_i), and find one if it exists.

Constraints

  • 1Q1001 \leq Q \leq 100
  • 0Ai109(1iQ)0 \leq A_i \leq 10^9(1 \leq i \leq Q)
  • 1Mi109(1iQ)1 \leq M_i \leq 10^9(1 \leq i \leq Q)

Inputs

Input is given from Standard Input in the following format:

Q
A_1 M_1
:
A_Q M_Q

Outputs

In the ii-th line, print 1-1 if there is no integer KiK_i that satisfies the condition. Otherwise, print an integer KiK_i not exceeding 2×10182 \times 10^{18} such that AiKiKiA_i^{K_i} ≡ K_i (mod(mod Mi)M_i). If there are multiple solutions, any of them will be accepted.

4
2 4
3 8
9 6
10 7
4
11
9
2

It can be seen that the condition is satisfied: 24=1642^4 = 16 ≡ 4 (mod(mod 4)4), 311=177147113^{11} = 177147 ≡ 11 (mod(mod 8)8), 99=38742048999^9 = 387420489 ≡ 9 (mod(mod 6)6) and 102=100210^2 = 100 ≡ 2 (mod(mod 7)7).

3
177 168
2028 88772
123456789 987654321
7953
234831584
471523108231963269