#include using namespace std; typedef int _loop_int; #define REP(i,n) for(_loop_int i=0;i<(_loop_int)(n);++i) const int inv[] = {0,1,5,0,7,2,0,4,8}; void solve(){ int n,x,a,b,m; scanf("%d%d%d%d%d",&n,&x,&a,&b,&m); if(n==1){ printf("%d\n",x%10); return; } int ab = 1; int tri = 0; int ans = 0; int ac = (n-1)%3; int bc = 2; bool flag = false; REP(i,n-1){ const int cur = x%10; flag |= cur!=0; if(tri==0){ ans += ab*cur%9; }else if(tri==1){ ans += ab*3*cur%9; } x = ((x^a)+b)%m; int aa = n-1-i; if(ac==0){ aa/=3; tri++; while(aa%3==0){ aa/=3; tri++; } ac=2; }else{ ac--; } int bb = i+1; if(bc==0){ bb/=3; tri--; while(bb%3==0){ bb/=3; tri--; } bc=2; }else{ bc--; } ab = ab*aa*inv[bb%9]%9; } const int cur = x%10; flag |= cur!=0; ans += cur; if(!flag){ puts("0"); return; } ans%=9; if(ans==0)ans=9; printf("%d\n",ans); } int main(){ int t; scanf("%d",&t); while(t--)solve(); return 0; }