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: Accepted)

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define REP(i,n) for(int i=0;i<(n);i++)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define int ll
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;

template<class T> inline void read(T &x){
	int f=0;x=0;char ch=getchar();
	for(;!isdigit(ch);ch=getchar())f|=(ch=='-');
	for(;isdigit(ch);ch=getchar())x=x*10+ch-'0';
	if(f)x=-x;
}

const int N=100005;
int mark[N],pr[N],cnt;
int p[20],c;

void init(int n){
	rep(i,2,n){
		if(mark[i]) continue;
		pr[++cnt]=i;
		for(int j=i;j<=n;j+=i) mark[j]=1;
	}
}

int getphi(int x){
	int res=1;
	rep(i,1,c) if(x%p[i]==0){
		res*=p[i]-1,x/=p[i];
		while(x%p[i]==0) x/=p[i],res*=p[i];
	}
	return res;
}

int power(int x,ll p,int m){
	int res=1;
	for(;p;p>>=1,x=(ll)x*x%m)
		if(p&1)res=(ll)res*x%m;
	return res;
}

int gcd(int a,int b,int &x,int &y){
	if(!b) return x=1,y=0,a;
	int r=gcd(b,a%b,y,x);
	return y-=a/b*x,r;
}

ll solve(int a,int m){
	if(m==1) return 1;
	int n=getphi(m),g=__gcd(m,n);
	int u=solve(a,g),v=power(a,u,m);
	int x,y,c=v-u,t=gcd(n,m,x,y);
	ll X=(ll)x*c/t%m,mod=(ll)m*n;
	return (ll)(n*X+u+mod)%mod+mod;
}

void rmain(){
	int a,m,t;
	read(a),read(m),a%=m;
	int g=__gcd(a,m);
	t=m,c=0;
	for(int i=1;pr[i]*pr[i]<=t;i++)
		if(t%pr[i]==0){
			p[++c]=pr[i];
			while(t%pr[i]==0) t/=pr[i];
		}
	if(t>=2) p[++c]=t;
	ll res=solve(a,m);
	assert(power(a,res,m)==res%m);
	cout<<res<<endl;
}

signed main(){
	int T; read(T); init(100000);
	while(T--) rmain();
	return 0;
}