#include <bits/stdc++.h> #define _overload(_1,_2,_3,name,...) name #define _rep(i,n) _range(i,0,n) #define _range(i,a,b) for(int i=int(a);i<int(b);++i) #define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__) using namespace std; using ll=long long; const int t_limit=100000; const int n_limit=10000000; const int num_idx[10]={0,0,1,0,2,5,0,4,3,0}; const int two_idx[6]={1,2,4,8,7,5}; int main(void){ int t=0,sum=0; scanf("%d",&t); assert(1<=t && t<=t_limit); rep(loop,t){ int n,x,a,b,m; scanf("%d %d %d %d %d",&n,&x,&a,&b,&m); assert(1<=n && n<=n_limit); assert(0<=x && x<=1e9); assert(0<=a && a<=1e9); assert(0<=b && b<=1e9); assert(1<=m && m<=1e9); sum+=n; bool allzero=true; int answer=0,num=n-1,den=1,two=0,three=0,tmp=0; rep(i,n){ int s=x%10; x=((x^a)+b)%m; if(s!=0) allzero=false; if(three<=1){ int cur=s; cur=s*two_idx[two%6]*(three?3:1); answer+=cur; } if(i==n-1) break; tmp=num; while(tmp%3==0) tmp/=3,three++; two+=(num_idx[tmp%9]); tmp=den; while(tmp%3==0) tmp/=3,three--; two+=(6-num_idx[tmp%9]); num--,den++; } answer%=9; if(allzero==false && answer==0) answer=9; printf("%d\n",answer); } assert(sum<=n_limit); return 0; }