// [7/26/2014 Sjm]
/*
此题看懂题意,就可以了。。。模拟+最短路。。。
*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef __int64 int64;
const int MAX = 1005;
const int INF = 0x3f3f3f3f;
int64 N, M, X0, X1, Y0, Y1;
int64 X[MAX*MAX], Y[MAX*MAX], Z[MAX*MAX], C[MAX][MAX];
int64 d[MAX];
bool used[MAX];
void Dijkstra(int64 s) {
fill(d, d + N, INF);
fill(used, used + N, false);
d[s] = 0;
while (true) {
int64 v = -1;
for (int64 u = 0; u < N; ++u) {
if (!used[u] && (-1 == v || d[u] < d[v])) {
v = u;
}
}
if (-1 == v) break;
used[v] = true;
for (int u = 0; u < N; ++u) {
d[u] = min(d[u], d[v] + C[v][u]);
}
}
}
int main() {
//freopen("input.txt", "r", stdin);
while (~scanf("%I64d %I64d %I64d %I64d %I64d %I64d", &N, &M, &X[0], &X[1], &Y[0], &Y[1])) {
Z[0] = ((X[0] * 90123) % 8475871 + Y[0] % 8475871) % 8475871 + 1;
Z[1] = ((X[1] * 90123) % 8475871 + Y[1] % 8475871) % 8475871 + 1;
for (int i = 2; i < N*N; ++i) {
X[i] = (12345 + (X[i - 1] * 23456) % 5837501 + (X[i - 2] * 34567) % 5837501 + (X[i - 1] * X[i - 2] * 45678) % 5837501) % 5837501;
Y[i] = (56789 + (Y[i - 1] * 67890) % 9860381 + (Y[i - 2] * 78901) % 9860381 + (Y[i - 1] * Y[i - 2] * 89012) % 9860381) % 9860381;
Z[i] = ((X[i] * 90123) % 8475871 + Y[i] % 8475871) % 8475871 + 1;
}
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
if (i == j) C[i][j] = 0;
else C[i][j] = Z[i*N + j];
}
}
/*
for (int i = 0; i < N*N; ++i) { cout << X[i] << " "; }
cout << endl;
for (int i = 0; i < N*N; ++i) { cout << Y[i] << " "; }
cout << endl;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
cout << C[i][j] << " ";
}
cout << endl;
}
cout << endl;
*/
Dijkstra(0);
int64 ans = INF;
for (int i = 1; i < N; ++i) {
ans = min(ans, d[i] % M);
}
printf("%d\n", ans);
}
return 0;
}