#include using namespace std; pair extgcd(long long a, long long b) { if (b == 0) return{ 1, 0 }; long long x, y; tie(x, y) = extgcd(b, a % b); return{ y, x - a / b * y }; } long long modulo(long long a, long long mod) { return (a % mod + mod) % mod; } long long modinv(long long a, long long mod) { return modulo(extgcd(a, mod).first, mod); } struct CombinationLucas { long long p, q; long long mod; vector F, invF; CombinationLucas(int n, long long p, long long q) : p(p), q(q), F(n), invF(n) { mod = 1; for (int i = 0; i < q; i++) { mod *= p; } F[0] = 1; for (long long i = 1; i < n; i++) { if (i % p == 0) { F[i] = F[i - 1]; } else { F[i] = F[i - 1] * i % mod; } } invF[n - 1] = modinv(F[n - 1], mod); for (long long i = n - 2; i >= 0; i--) { if ((i + 1) % p == 0) { invF[i] = invF[i + 1]; } else { invF[i] = invF[i + 1] * (i + 1) % mod; } } } int count(int n) { long long res = 0; n /= p; while (n > 0) res += n, n /= p; return res; } long long operator()(int n, int r) { if (n < 0 || r < 0 || n < r) return 0; long long result = F[n % (mod * 2)] * invF[(n - r) % (mod * 2)] % mod * invF[r % (mod * 2)] % mod; int c = count(n) - count(r) - count(n - r); if (c >= 2) return 0; if (c == 1) (result *= 3) %= mod; return result; } }; int main() { int T; cin >> T; CombinationLucas cb(30, 3, 2); while (T--) { long long n, x, a, b, m; scanf("%lld %lld %lld %lld %lld", &n, &x, &a, &b, &m); bool zero = true; long long ans = 0; for (int i = 0; i < n; i++) { if (x != 0) zero = false; ans += cb(n - 1, i) * (x % 10); x = ((x ^ a) + b) % m; } ans %= 9; if (ans == 0) ans = 9; if (zero) ans = 0; printf("%lld\n", ans); } }