#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define nL “\n”
#define pb push_back
ll p;
ll k;
vector b, c;
vector<vector> multiply(vector<vector> A, vector<vector> B)
{
vector<vector> C(k + 2, vector(k + 2)); // matrix multiplication (A * B) => store in C
for (int i = 1; i <= k+1; i++)
{
for (int j = 1; j <= k+1; j++)
{
for (int x = 1; x <= k+1; x++)
{
C[i][j] = (C[i][j] + (A[i][x] * B[x][j]) % p) % p;
}
}
}
return C;
}
vector<vector> power(vector<vector> A, int p)
{
if (p == 1)
return A;
if (p & 1) //odd
{
return multiply(A, power(A, p - 1));
}
vector<vector<ll>> X = power(A, p / 2); //even
return multiply(X, X);
}
ll compute(ll n)
{
if (n == 0)
return 0;
if (n <= k)
return b[n - 1];
// step 1 find F1(stores first k terms)
vector<ll> F1(k + 2);
F1[1] = 0;
for (int i = 2; i <= k+1; i++)
{
F1[i] = b[i - 2];
}
//step2 - compute T(transformation matrix)
vector<vector<ll>> T(k + 2, vector<ll>(k + 2));
for (int i = 1; i <= k+1; i++)
{
for (int j = 1; j <= k+1; j++)
{
if(i == 1 && j == 1)
{
T[i][j] = 1;
continue;
}
if(i == k+1 && j > 1)
{
T[i][j] = c[k - j + 1];
continue;
}
if(j == i+1)
{
T[i][j] = 1;
}
else
T[i][j] = 0;
}
}
//step3 - cal T ^ n
T = power(T, n);
//step 4 - cal res by T^n-1 * F1
ll res = 0;
for (int i = 1; i <= k+1; i++)
{
res = (res + (T[1][i] * F1[i]) % p) % p;
}
return res;
}
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
ll t, n, num;
cin >> t;
while (t--)
{
cin >> k;
for (int i = 1; i <= k; i++)
{
cin >> num;
b.pb(num);
}
for (int i = 1; i <= k; i++)
{
cin >> num;
c.pb(num);
}
ll m, n;
cin >> m >> n >> p;
ll Sn = compute(n);
ll Sm1 = compute(m-1);
ll reqSum = (Sn - Sm1 + p) % p;
cout << reqSum << nL;
b.clear();
c.clear();
}
return 0;
}