#include <cstdio>
#include <fstream>
#include <cstdlib>
using namespace std;
struct cow_t {
long long W, U;
};
int comp (const void *a, const void *b)
{
const cow_t *ca = (const cow_t*)a, *cb = (const cow_t*)b;
if (ca->U != cb->U)
return cb->U - ca->U;
else
return ca->W - cb->W;
}
int main ()
{
ifstream fin("farmoff.in");
ofstream fout("farmoff.out");
long long N, a, b, c, d, e, f, g, h, M;
fin >> N >> a >> b >> c >> d >> e >> f >> g >> h >> M;
cow_t cow[3*N];
for (int i=0; i<3*N; i++)
{
long long j = i%d;
cow[i].W = (a%d*j%d*j%d*j%d*j%d*j%d+b%d*j%d*j%d+c%d)%d;
j= i%h;
cow[i].U = (e%h*j%h*j%h*j%h*j%h*j%h+f*j%h*j%h*j%h+g%h)%h;
}
qsort(cow, 3*N, sizeof(cow_t), comp);
long long minw = 0;
for (int i=0; i<N; i++)
minw += cow[i].W;
fout << minw << "\n";
return 0;
}