#define _CRT_SECURE_NO_WARNINGS
#define _SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING
#include <bits/stdc++.h>
using namespace std;
#define CRP(t, x) const t &x
#define OPL(t, x) bool operator<(CRP(t, x)) const
#define FIL(x, v) memset(x, v, sizeof(x))
#define CLR(x) FIL(x, 0)
#define NE1(x) FIL(x, -1)
#define INF(x) FIL(x, 0x3f)
typedef long long ll, i64;
ll ans[1005], Q[1005];
unordered_map<ll, int> mp;
int main()
{
    ll T, n, x0, a, b, p, q, v;
    scanf("%lld", &T);
    while (T--)
    {
        NE1(ans), mp.clear();
        scanf("%lld%lld%lld%lld%lld%lld", &n, &x0, &a, &b, &p, &q);
        for (int i = 0; i < q; i++)
            scanf("%lld", Q + i), mp[Q[i]] = i;
        int ed = min(n, p - 1);
        v = x0;
        unordered_map<ll, int>::iterator ite;
        for (int i = 0; i <= ed; i++, v = (a * v + b) % p)
        {
            ite = mp.find(v);
            if (ite != mp.end() && ans[ite->second] == -1) ans[ite->second] = i;
        }
        for (int i = 0; i < q; i++)
            printf("%lld\n", ans[mp[Q[i]]]);
    }
    return 0;
}