#include //#include using namespace std; // using namespace atcoder; // using mint = modint1000000007; // const int mod = 1000000007; // using mint = modint998244353; // const int mod = 998244353; // const int INF = 1e9; // const long long LINF = 1e18; #define rep(i, n) for (int i = 0; i < (n); ++i) #define rep2(i, l, r) for (int i = (l); i < (r); ++i) #define rrep(i, n) for (int i = (n)-1; i >= 0; --i) #define rrep2(i, l, r) for (int i = (r)-1; i >= (l); --i) #define all(x) (x).begin(), (x).end() #define allR(x) (x).rbegin(), (x).rend() #define P pair template inline bool chmax(A &a, const B &b) { if (a < b) { a = b; return true; } return false; } template inline bool chmin(A &a, const B &b) { if (a > b) { a = b; return true; } return false; } static inline int inv_mod9(int x) { switch (x % 9) { case 1: return 1; case 2: return 5; case 4: return 7; case 5: return 2; case 7: return 4; case 8: return 8; } return 0; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int n; long long x, a, b, m; cin >> n >> x >> a >> b >> m; int N = n - 1; long long r = x; long long sum = 0; int ans = 0; // C(N,0)=1 int unit = 1; // 3 を除いた部分 mod 9 int e = 0; // 3 の指数 rep(i, n) { if (i) { r = ((r ^ a) + b) % m; } sum += r; int coef; if (e >= 2) { coef = 0; } else if (e == 1) { coef = unit * 3 % 9; } else { coef = unit; } ans += coef * (int)(r % 10); ans %= 9; if (i == N) continue; long long num = N - i; long long den = i + 1; int cnum = 0; while (num % 3 == 0) { num /= 3; cnum++; } int cden = 0; while (den % 3 == 0) { den /= 3; cden++; } e += cnum - cden; unit = unit * (int)(num % 9) % 9; unit = unit * inv_mod9((int)(den % 9)) % 9; } if (ans == 0 && sum != 0) ans = 9; cout << ans << '\n'; } return 0; }