#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<b;i++)




const int inv[9] = { 0, 1, 5, 0, 7, 2, 0, 4, 8 };
int modpow(int a, int n, int mod = 9) {
    a %= mod;
    if (a == 0) return 0;
    int r = 1;
    while (n) r = r*((n % 2) ? a : 1) % mod, a = a*a%mod, n >>= 1;
    return r;
}
int sol(int N, int X, int A, int B, int M) {
    vector<int> v;
    v.push_back(X);
    rep(i, 0, N - 1) v.push_back(((v[i] ^ A) + B) % M);
    rep(i, 0, N) v[i] %= 10;
    int sm = 0;
    for (int i : v) sm += i;
    if (sm == 0) return 0;

    int a = 1, b = 1, t = 0;
    int res = 0;
    int n = v.size();
    rep(i, 0, n) {
        int c = a * inv[b] * modpow(3, t) % 9;
        res = (res + v[i] * c) % 9;
        a *= (n - 1 - i);
        b *= (i + 1);
        while (a % 3 == 0 && 0 < a) a /= 3, t++;
        while (b % 3 == 0 && 0 < b) b /= 3, t--;
        a %= 9; b %= 9;
    }
    if (res == 0) res = 9;
    return res;
}
//-----------------------------------------------------------------------------------
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);

    int T; cin >> T;
    rep(t, 0, T) {
        int N, X, A, B, M;
        cin >> N >> X >> A >> B >> M;
        printf("%d\n", sol(N, X, A, B, M));
    }
}