#include <cstdio>
#include <algorithm>
#define pii pair <int, int>
#define f first
#define s second
using namespace std;
int t0, t1, a, b, x, y, z, M;
int p1, p2, x11, x12, x21, x22, pas1, pas2;
long long ca[8192], cb[8192];
int nxt (int tn2, int tn1)
{
int rez = 1LL * (ca[tn2] + ca[tn1] + 1LL * z);
rez -= (rez >= M) * M;
rez -= (rez >= M) * M;
return rez;
}
void solve ()
{
for (;;)
{
if (x11 == x21 && x12 == x22 && p2 > p1 + 1) return;
int aux;
if (pas1)
{
aux = nxt (x11, x12);
x11 = x12;
x12 = aux;
++p1;
}
aux = nxt (x21, x22);
x21 = x22;
x22 = aux;
++p2;
if (pas2 > 0)
{
aux = nxt (x21, x22);
x21 = x22;
x22 = aux;
++p2;
}
}
}
int main ()
{
freopen ("rsir.in", "r", stdin);
freopen ("rsir.out", "w", stdout);
scanf ("%d %d %d %d %d %d %d %d", &t0, &t1, &a, &b, &x, &y, &z, &M);
if (t0 >= M) t0 %= M;
if (t1 >= M) t1 %= M;
if (a >= M) a %= M;
if (b >= M) b %= M;
if (x >= M) x %= M;
if (y >= M) y %= M;
if (z >= M) z %= M;
for (int i = 0; i < M; ++i)
{
ca[i] = 1LL * i * i * a + 1LL * i * x;
if (ca[i] >= 1LL * M) ca[i] %= 1LL * M;
cb[i] = 1LL * i * i * b + 1LL * i * y;
if (cb[i] >= 1LL * M) cb[i] %= 1LL * M;
/*ca[i] *= 1LL * a;
if (ca[i] >= 1LL * M) ca[i] %= 1LL * M;
ca[i] += 1LL * (1LL * x * i) % (1LL * M);
if (ca[i] >= 1LL * M) ca[i] %= 1LL * M;
cb[i] = 1LL * i * i;
if (cb[i] >= 1LL * M) cb[i] %= 1LL * M;
cb[i] *= 1LL * b;
if (cb[i] >= 1LL * M) cb[i] %= 1LL * M;
cb[i] += 1LL * (1LL * y * i) % (1LL * M);
if (cb[i] >= 1LL * M) cb[i] %= 1LL * M;*/
}
long long n;
scanf ("%lld", &n);
p1 = 0, p2 = 0, x11 = t0, x12 = t1, x21 = t0, x22 = t1, pas1 = 1, pas2 = 2;
solve ();
p1 = 0, x11 = t0, x12 = t1, pas2 = 1;
solve ();
int st = p1;
p2 = p1, x21 = x11, x22 = x12, pas1 = 0, pas2 = 1;
solve ();
int per = p2 - p1;
if (n < 1LL * st)
{
x11 = t0, x12 = t1;
for (int i = 1; i <= n; ++i)
{
int aux = nxt (x11, x12);
x11 = x12;
x12 = aux;
}
printf ("%d\n", x11);
return 0;
}
n -= 1LL * st;
n %= 1LL * per;
for (int i = 1; i <= n; ++i)
{
int aux = nxt (x11, x12);
x11 = x12;
x12 = aux;
}
printf ("%d\n", x11);
return 0;
}