#include using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) //------------------------------------------------------- ll mo; const int MAT=2; struct Mat { ll v[MAT][MAT]; Mat(){ZERO(v);};}; Mat mulmat(Mat& a,Mat& b,int n=MAT) { ll mo2=4*mo*mo; int x,y,z; Mat r; FOR(x,n) FOR(y,n) r.v[x][y]=0; FOR(x,n) FOR(z,n) FOR(y,n) { r.v[x][y] += a.v[x][z]*b.v[z][y]; if(r.v[x][y]>mo2) r.v[x][y] -= mo2; } FOR(x,n) FOR(y,n) r.v[x][y]%=mo; return r; } Mat powmat(ll p,Mat a,int n=MAT) { int i,x,y; Mat r; FOR(x,n) FOR(y,n) r.v[x][y]=0; FOR(i,n) r.v[i][i]=1; while(p) { if(p%2) r=mulmat(r,a,n); a=mulmat(a,a,n); p>>=1; } return r; } ll modpow(ll a, ll n = mo-2) { ll r=1; while(n) r=r*((n%2)?a:1)%mo,a=a*a%mo,n>>=1; return r; } Mat revmat(Mat a,int n=MAT) { Mat m; int x,y,z; FOR(x,n) FOR(y,n) m.v[x][y]=x==y; FOR(x,n) { for(y=x;y conv(Mat M) { vector V; V.push_back(M.v[0][0]); V.push_back(M.v[0][1]); V.push_back(M.v[1][0]); V.push_back(M.v[1][1]); return V; } void solve() { int i,j,k,l,r,x,y; string s; cin>>mo; cin>>A.v[0][0]>>A.v[0][1]; cin>>A.v[1][0]>>A.v[1][1]; cin>>B.v[0][0]>>B.v[0][1]; cin>>B.v[1][0]>>B.v[1][1]; vector V[2]; for(i=1;1LL*i*i<=mo-1;i++) if((mo-1)%i==0) { V[0].push_back(i); if(i*i!=mo-1) V[0].push_back((mo-1)/i); } if(conv(powmat(mo*(mo-1)+1,A))==conv(A)) { V[1].push_back(1); V[1].push_back(mo); } else if(conv(powmat((mo+1)*(mo-1)+1,A))==conv(A)) { for(i=1;1LL*i*i<=mo+1;i++) if((mo+1)%i==0) { V[1].push_back(i); if(i*i!=mo+1) V[1].push_back((mo+1)/i); } } else { assert(0); } sort(ALL(V[0])); sort(ALL(V[1])); ll per=(mo-1)*(mo+1); FORR(a,V[0]) FORR(b,V[1]) if(a*b>1 && a*b,int> M; M[conv(E)]=0; for(i=1;1LL*i*i<=mo;i++) { E=mulmat(RA,E); M[conv(E)]=i; QA=mulmat(QA,A); } j=i-1; Mat A2; A2.v[0][0]=A2.v[1][1]=1; ll P=0; ll ret=1LL<<60; while(P<=mo) { if(M.count(conv(A2))) { ret=min(ret,(P+M[conv(A2)])%per); } A2=mulmat(A2,QA); P+=j; } if(ret==1LL<<60) ret=-1; cout<