#include<algorithm>
#include<bitset>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<deque>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<vector>
using namespace std;
#define dbg(x) (cout<<#x<<" = "<<(x)<<'\n')
#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "rsir";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif
typedef long long int lld;
typedef pair<int, int> PII;
typedef pair<int, lld> PIL;
typedef pair<lld, int> PLI;
typedef pair<lld, lld> PLL;
const int INF = (1LL << 31) - 1;
const lld LINF = (1LL << 62) - 1;
const int dx[] = {1, 0, -1, 0, 1, -1, 1, -1};
const int dy[] = {0, 1, 0, -1, 1, -1, -1, 1};
lld N;
int MOD;
int T[4];
int a, b, x, y, z;
int P[7005];
int main() {
int i, j;
int p, q, p1, p2, q1, q2;
#ifndef ONLINE_JUDGE
freopen(inputFile.c_str(), "r", stdin);
freopen(outputFile.c_str(), "w", stdout);
#endif
scanf("%d%d", &T[0], &T[1]);
scanf("%d%d", &a, &b);
scanf("%d%d%d", &x, &y, &z);
scanf("%d%lld", &MOD, &N);
T[0] %= MOD;
T[1] %= MOD;
for(i = 0; i <= MOD; i++)
P[i] = (i * i) % MOD;
p1 = q1 = T[0];
p2 = q2 = T[1];
p = q = (a * P[p1] + b * P[p2] + x * p1 + y * p2 + z) % MOD;
i = j = 2;
do {
p = (a * P[p1] + b * P[p2] + x * p1 + y * p2 + z) % MOD;
p1 = p2;
p2 = p;
i++;
q = (a * P[q1] + b * P[q2] + x * q1 + y * q2 + z) % MOD;
q1 = q2;
q2 = q;
q = (a * P[q1] + b * P[q2] + x * q1 + y * q2 + z) % MOD;
q1 = q2;
q2 = q;
j += 2;
} while(p1 != q1 || p2 != q2);
N %= (j - i);
if(N == 0)
printf("%d\n", T[0]);
else if(N == 1)
printf("%d\n", T[1]);
else {
p1 = T[0];
p2 = T[1];
i = 2;
do {
p = (a * P[p1] + b * P[p2] + x * p1 + y * p2 + z) % MOD;
p1 = p2;
p2 = p;
i++;
} while(i <= N);
printf("%d\n", p);
}
return 0;
}