#pragma GCC optimize ("O3") #pragma GCC target ("avx") #include #include #include #include #include #include #include #include #include #include #include #include #include #define getchar getchar_unlocked #define putchar putchar_unlocked #define _rep(_1, _2, _3, _4, name, ...) name #define rep2(i, n) rep3(i, 0, n) #define rep3(i, a, b) rep4(i, a, b, 1) #define rep4(i, a, b, c) for (int i = int(a); i < int(b); i += int(c)) #define rep(...) _rep(__VA_ARGS__, rep4, rep3, rep2, _)(__VA_ARGS__) using namespace std; using i8 = signed char; using i16 = signed short; using i64 = long long; using u8 = unsigned char; using u32 = unsigned; using u64 = unsigned long long; using f80 = long double; struct FastDiv { FastDiv() {} FastDiv(u32 n) : m(n) { s = (n == 1) ? 0 : 32 + __lg(n - 1); x = ((u64(1) << s) + n - 1) / n; } friend u32 operator / (u32 n, FastDiv d) { return u64(n) * d.x >> d.s; } friend u32 operator % (u32 n, FastDiv d) { return n - n / d * d.m; } u32 m, s, x; }; constexpr u32 mul_inv(u32 a, u32 res=1, u32 e=5) { return e == 0 ? res : mul_inv(a, res *= 2 - a * res, e - 1); } int get_int() { int c, n; while ((c = getchar()) < '0'); n = c - '0'; while ((c = getchar()) >= '0') n = n * 10 + (c - '0'); return n; } void solve() { constexpr u32 inv3 = mul_inv(3); const u32 t3 = u32(-1) / 3; const u32 invs[] = {0, 1, 5, 0, 7, 2, 0, 4, 8}; int T; while (~scanf("%d", &T)) { rep(_, T) { int n = get_int(), x = get_int(); int a = get_int(), b = get_int(), m = get_int(); auto d = FastDiv(m); int e = 0, y = x % 10, t = y; i64 ans = y; u32 binom = 1; rep(i, n - 1) { x = ((x ^ a) + b) % d; u32 numer = n - 1 - i, denom = i + 1; for (; numer * inv3 <= t3; numer *= inv3, ++e); for (; denom * inv3 <= t3; denom *= inv3, --e); binom = binom * numer * invs[denom % 9] % 9; t |= y = x % 10; if (e < 2) ans += y * binom * (2 * e + 1); } if (!t) puts("0"); else printf("%d\n", (ans + 8) % 9 + 1); } } } int main() { auto beg = clock(); solve(); auto end = clock(); fprintf(stderr, "%.3f sec\n", double(end - beg) / CLOCKS_PER_SEC); }