#include #include void solve() { using namespace std; int n, x, a, b, m; cin >> n >> x >> a >> b >> m; int r = x, c = 1, e = 0, ans = 0; constexpr int inv[] = {0, 1, 5, 0, 7, 2, 0, 4, 8}; for (int i = 0; i < n; i++) { int s = r % 10; if (e == 0) { ans += s * c; } else if (e == 1) { ans += s * c * 3; } ans %= 9; if (i == n - 1) { break; } int k = n - i - 1; while (k % 3 == 0) { k /= 3; e++; } c *= k; k = i + 1; while (k % 3 == 0) { k /= 3; e--; } c *= inv[k]; c %= 3; r ^= a; r += b; r %= m; } if (ans == 0) { ans = 9; } cout << ans << "\n"; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int t; std::cin >> t; while (t--) { solve(); } }