#nt1002. 指数方程2

指数方程2

Index Equation 2

Problem Description

Answer TT queries. Each query gives a number a,b,ma, b, m; output the smallest non-negative integer xx satisfying ax≡b(modm)a^x \equiv b \pmod {m}.

Input Format

The first line contains one integer TT. The following TT lines each contain three integers a,b,ma, b, m.

Output Format

One integer: the smallest non-negative integer solution; if there is no solution, output -1.

Sample Input

3
2 0 1024
123 456 789
114514 1919810 504289861

Sample Output

10
49
2

Constraints

For all data, it is guaranteed that T≤100T\leq 100, 1≤a<m≤1091\leq a < m \leq 10^9, 0≤b<m≤1090\leq b < m \leq 10^9.

Hint

  • This asks for the discrete logarithm. Use the Baby-step Giant-step (BSGS) algorithm, accounting for the case b=0b=0 (a solution exists iff aa is not coprime to mm in a way that eventually yields 0, or simply check small xx first) and extend it to the general (non-coprime) case with the extended BSGS method.