#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); } int F[100], invF[100]; int count(int n) { int res = 0; n /= 3; while (n > 0) res += n, n /= 3; return res; } void init() { F[0] = 1; for (long long i = 1; i < 50; i++) { if (i % 3 == 0) { F[i] = F[i - 1]; } else { F[i] = F[i - 1] * i % 9; } } invF[49] = modinv(F[49], 9); for (long long i = 48; i >= 0; i--) { if ((i + 1) % 3 == 0) { invF[i] = invF[i + 1]; } else { invF[i] = invF[i + 1] * (i + 1) % 9; } } }; int main() { int T; cin >> T; init(); while (T--) { long long n, x, a, b, m; scanf("%lld %lld %lld %lld %lld", &n, &x, &a, &b, &m); bool zero = true; n--; int N = count(n); int L = 0; int R = N; long long ans = 0; for (int i = 0; i <= n; i++) { if (x != 0) zero = false; long long comb = F[n % 6] * invF[(n - i) % 6] * invF[i % 6]; int cnt = N - L - R; if (cnt >= 2) comb = 0; else if (cnt == 1) comb *= 3; ans += comb * (x % 10); if (i < n) { for (int t = i + 1; t > 0 && t % 3 == 0; t /= 3) L++; for (int t = n - i; t > 0 && t % 3 == 0; t /= 3) R--; } x = ((x ^ a) + b) % m; } ans %= 9; if (ans == 0) ans = 9; if (zero) ans = 0; printf("%lld\n", ans); } }