#include #define rep(i,n) for(int i=0;i<(int)(n);i++) #define rep1(i,n) for(int i=1;i<=(int)(n);i++) #define all(c) c.begin(),c.end() #define pb push_back #define fs first #define sc second #define show(x) cout << #x << " = " << x << endl #define chmin(x,y) x=min(x,y) #define chmax(x,y) x=max(x,y) using namespace std; template ostream& operator<<(ostream& o,const pair &p){return o<<"("< ostream& operator<<(ostream& o,const vector &vc){o<<"sz = "<>T; rep(tq,T){ int N,x,a,b,m; cin>>N>>x>>a>>b>>m; int res = 0; int X = 0, Y = 1; // C = 3^X * Y bool all0 = 1; rep(i,N){ int p = x%10; if(p){ all0 = 0; } if(X==0){ res += p*Y; }else if(X==1){ res += p*3*Y; } res %= 9; x = ((x^a)+b)%m; // C = C*(N-1-i)/(i+1); if(i==N-1) break; { int a = N-1-i; while(a%3==0){ a/=3; X++; } a %= 9; Y *= a; Y %= 9; } { int a = i+1; while(a%3==0){ a/=3; X--; } a %= 9; int b; if(a==1) b = 1; if(a==2) b = 5; if(a==4) b = 7; if(a==5) b = 2; if(a==7) b = 4; if(a==8) b = 8; Y *= b; Y %= 9; } } if(!all0 && res==0) res = 9; cout<