#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; while (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; int 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; if (cnt3 <= 1) { int two = nPi * inv[iPi]; ans += two * (cnt3 == 0 ? 1 : 3) * d; } auto num = decomp(n - i); auto den = decomp(i + 1); (nPi *= num.first) %= 9; (iPi *= den.first) %= 9; num3 += num.second; den3 += den.second; } ans %= 9; if (ans == 0) ans = 9; if (z) ans = 0; out(ans); } }