#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); } long long 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; } } }; long long cache[1000000]; long long FF(int n) { if (n == 0) return 1; return F[n % 18] * FF(n / 3) % 9; } long long invFF(int n) { if (n < 1000000) return cache[n]; return invF[n % 18] * invFF(n / 3) % 9; } int main() { int T; cin >> T; init(); cache[0] = 1; for (int i = 1; i < 1000000; i++) { cache[i] = invF[i % 18] * cache[i / 3] % 9; } 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; long long xF = FF(n); for (int i = 0; i <= n; i++) { if (x != 0) zero = false; long long comb = xF * invFF(n - i) * invFF(i); int cnt = N - L - R; if (cnt >= 2) comb = 0; else if (cnt == 1) comb *= 3; assert(cnt >= 0); (ans += comb * (x % 10)) %= 9; 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); } }