#include using namespace std; #define rep(i,a,b) for(int i=a;i>= 1; return r; } int sol(int N, int X, int A, int B, int M) { int a = 1, b = 1, t = 0; int v = X; int isAll0 = true; int res = 0; rep(i, 0, N) { int vv = v % 10; if (vv) isAll0 = false; int c = a * inv[b] * modpow(3, t) % 9; res = (res + vv * c) % 9; a *= (N - 1 - i); b *= (i + 1); while (a % 3 == 0 && 0 < a) a /= 3, t++; while (b % 3 == 0 && 0 < b) b /= 3, t--; a %= 9; b %= 9; v = ((v ^ A) + B) % M; } if (isAll0) return 0; if (res == 0) res = 9; return res; } //----------------------------------------------------------------------------------- int main() { cin.tie(0); ios::sync_with_stdio(false); int T; cin >> T; rep(t, 0, T) { int N, X, A, B, M; cin >> N >> X >> A >> B >> M; printf("%d\n", sol(N, X, A, B, M)); } }