#pragma GCC optimize ("O3") #include using namespace std; #ifndef LOCAL #define getchar getchar_unlocked #define putchar putchar_unlocked #endif int in() { int n, c; while ((c = getchar()) < '0') if (c == EOF) abort(); n = c - '0'; while ((c = getchar()) >= '0') n = n * 10 + c - '0'; return n; } void out(int n) { int res[11], i = 0; do { res[i++] = n % 10, n /= 10; } while (n); while (i) putchar(res[--i] + '0'); putchar('\n'); } int inv[] = { 0, 1, 5, 0, 7, 2, 0, 4, 8 }; pair decomp(int n) { if (n == 0) return{ 0, 0 }; int three = 0; for (; n % 3 == 0; n /= 3) three++; return{ n, three }; } int main() { int T = in(); while (T--) { int n = in() - 1, x = in(), a = in(), b = in(), m = in(); bool z = true; int nPi = 1, iPi = 1, num3 = 0, den3 = 0; int64_t ans = 0; for (int i = 0; i <= n; i++, x = ((x ^ a) + b) % m) { int d = x % 10; if (d != 0) z = false; int cnt3 = num3 - den3; ans += nPi * inv[iPi] * (cnt3 == 0 ? 1 : cnt3 == 1 ? 3 : 0) * d; if (i < n) { for (nPi *= n - i; nPi % 3 == 0; nPi /= 3) num3++; for (iPi *= i + 1; iPi % 3 == 0; iPi /= 3) den3++; nPi %= 9; iPi %= 9; } } out(z ? 0 : (ans - 1) % 9 + 1); } }