#include #include #include #include #include #define repeat(i,n) for (int i = 0; (i) < (n); ++(i)) #define repeat_from(i,m,n) for (int i = (m); (i) < (n); ++(i)) #define whole(f,x,...) ([&](decltype((x)) y) { return (f)(begin(y), end(y), ## __VA_ARGS__); })(x) using namespace std; template void setmax(T & a, T const & b) { if (a < b) a = b; } template auto vectors(T a, X x) { return vector(x, a); } template auto vectors(T a, X x, Y y, Zs... zs) { auto cont = vectors(a, y, zs...); return vector(x, cont); } pair zero(int k) { int z = 0; while (k % 3 == 0) { k /= 3; z += 1; } return { k, z }; } int pack(int k, int z) { return z * 9 + k; } pair unpack(int n) { return { n % 9, n / 9 }; } const int inv[9] = { 0, 1, 5, 0, 7, 2, 0, 4, 8 }; int choose(int n, int r) { static vector fact(1, pack(1, 0)); if (fact.size() <= n) { int l = fact.size(); fact.resize( n + 1); repeat_from (i,l,n+1) { int pk, pz; tie(pk, pz) = unpack(fact[i-1]); int k, z; tie(k, z) = zero(i); fact[i] = pack(pk * k % 9, pz + z); } } r = min(r, n - r); int pk, pz; tie(pk, pz) = unpack(fact[n]); int qk, qz; tie(qk, qz) = unpack(fact[r]); int rk, rz; tie(rk, rz) = unpack(fact[n-r]); int p = pk * inv[qk] * inv[rk] % 9; int z = pz - qz - rz; assert (z >= 0); return z == 0 ? p : z == 1 ? p * 3 % 9 : 0; } int main() { int t; cin >> t; while (t --) { int n, x, a, b, m; cin >> n >> x >> a >> b >> m; bool zero = true; int acc = x % 10; if (x % 10 != 0) zero = false; repeat_from (i,1,n) { x = ((x ^ a) + b) % m; acc = (acc + x % 10 * choose(n-1, i)) % 9; if (x % 10 != 0) zero = false; } if (not zero and acc == 0) acc = 9; cout << acc << endl; } return 0; }