#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define popcount __builtin_popcount using namespace std; typedef long long int ll; typedef pair P; ll p; using arr=array; using Mat=array; Mat matmul(Mat a, Mat b){ Mat c={}; for(int i=0; i<2; i++){ for(int j=0; j<2; j++){ for(int k=0; k<2; k++){ (c[i][j]+=a[i][k]*b[k][j])%=p; } } } return c; } Mat matpow(Mat a, ll k){ Mat ap=a, ans={}; ans[0][0]=ans[1][1]=1; while(k){ if(k&1) ans=matmul(ap, ans); ap=matmul(ap, ap); k>>=1; } return ans; } Mat e, ainv; bool nuee; ll matlog(Mat a, Mat b, ll d){ ll sq=1; while(sq*sq> vp(sq); vp[0]=make_pair(e, 0); for(int i=1; i x, pair y){ for(int i=0; i<2; i++){ for(int j=0; j<2; j++){ if(x.first[i][j]!=y.first[i][j]) return x.first[i][j]>=1; } return ans; } ll inv(ll a, ll m){ ll b=m, x=1, y=0; while(b>0){ ll t=a/b; swap(a-=t*b, b); swap(x-=t*y, y); } return (x%m+m)%m; } ll discretelog(ll x, ll y, ll m){ ll p=1%m; for(int i=0; i<=30; i++){ if(p==y) return i; (p*=x)%=m; } ll g=gcd(x, m); ll m1=m; for(ll i=2; i*i<=g; i++){ if(g%i==0){ while(g%i==0) g/=i; while(m1%i==0) m1/=i; } } if(g>1){ while(m1%g==0) m1/=g; } if(y%(m/m1)!=0) return -1; x%=m1, y%=m1; ll d=1; while(d*d mp; //yx^(-b) ll y1=y; for(ll i=0; isecond; } (q*=xd)%=m1; } return -1; } ll order(ll a){ if(a==1) return 1; return discretelog(a, inv(a, p), p)+1; } int main() { cin>>p; Mat a, b; cin>>a[0][0]>>a[0][1]>>a[1][0]>>a[1][1]>>b[0][0]>>b[0][1]>>b[1][0]>>b[1][1]; if(a==b){ cout<<1<0) q=0; if(matpow(a, q*m+r)==b) cout<