Problem:
Score : 1400 points

Problem Statement

Process the Q queries below.

You are given two integers A_i and M_i. Determine whether there exists a positive integer K_i not exceeding 2 × 10^{18} such that A_i^{K_i} ≡ K_i (mod M_i), and find one if it exists.

Constraints

1 \leq Q \leq 100

0 \leq A_i \leq 10^9(1 \leq i \leq Q)

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 i-th line, print -1 if there is no integer K_i that satisfies the condition.
Otherwise, print an integer K_i not exceeding 2 × 10^{18} such that A_i^{K_i} ≡ K_i (mod M_i). If there are multiple solutions, any of them will be accepted.

Sample Input 1

4
2 4
3 8
9 6
10 7

Sample Output 1

4
11
9
2

It can be seen that the condition is satisfied: 2^4 = 16 ≡ 4 (mod 4), 3^{11} = 177147 ≡ 11 (mod 8), 9^9 = 387420489 ≡ 9 (mod 6) and 10^2 = 100 ≡ 2 (mod 7).

Sample Input 2

3
177 168
2028 88772
123456789 987654321

Sample Output 2

7953
234831584
471523108231963269

Solution in C++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;

LL Pow(LL a,LL b,LL p)
{
    LL ans=1;
    for(;b;b>>=1,a=a*a%p)
        if(b&1) ans=ans*a%p;
    return ans;
}

LL exgcd(LL a,LL b,LL &x,LL &y)
{
    if(!b){x=1;y=0;return a;}
    LL g=exgcd(b,a%b,x,y);
    LL t=x;x=y;y=t-(a/b)*y;
    return g;
}

LL phi(LL x)
{
    LL ans=x;
    for(LL i=2;i*i<=x;i++)
    {
        if(x%i) continue;
        while(x%i==0) x/=i;
        ans=ans/i*(i-1);
    }
    if(x>1) ans=ans/x*(x-1);
    return ans;
}

LL solve(LL a,LL m)
{
    if(m==1) return 1;
    LL h=phi(m),g=__gcd(m,h);
    LL t=solve(a,g);
    //if(t==-1) return -1;
    LL x,y,gg=exgcd(h,m,x,y);
    LL at=Pow(a,t,m),c=at-t;
    //if(c%gg) return -1;
    LL tmp=-y*(c/gg);
    LL ans=tmp*m+at,ttt=m/g*h;
    ans=(ans%ttt+ttt)%ttt+ttt;
    return ans;
}

int main()
{
    int T,a,m;
    cin>>T;
    while(T--)
    {
        cin>>a>>m;
        cout<<solve(a,m)<<"\n";
    }
    return 0;
}