#include <iostream>
#include <cstring>
using namespace std;
const int MAX = 1000005;
int p, a, b, c, d, xa, ya, xb, yb;
int nexta[MAX], nextb[MAX];
bool mark[MAX];
void go()
{
a = nexta[a];
b = nextb[b];
}
int main()
{
ios::sync_with_stdio(false);
cin >> p >> a >> c >> xa >> ya >> b >> d >> xb >> yb;
for (int i = 0; i < p; i++)
{
nexta[i] = (1LL * i * xa + ya) % p;
nextb[i] = (1LL * i * xb + yb) % p;
}
long long ans = 0;
while (a != c && !mark[a])
{
mark[a] = true;
go();
ans++;
}
if (mark[a])
{
cout << -1 << endl;
return 0;
}
if (b == d)
{
cout << ans << endl;
return 0;
}
int alen = 0;
go();
alen++;
ans++;
memset(mark, false, sizeof(mark));
while (a != c && !mark[a])
{
mark[a] = true;
go();
ans++;
alen++;
}
if (mark[a])
{
cout << -1 << endl;
return 0;
}
if (b == d)
{
cout << ans << endl;
return 0;
}
memset(mark, false, sizeof(mark));
while (b != d && !mark[b])
{
mark[b] = true;
go();
ans++;
}
if (mark[b])
{
cout << -1 << endl;
return 0;
}
if (a == c)
{
cout << ans << endl;
return 0;
}
int blen = 0;
go();
blen++;
ans++;
memset(mark, false, sizeof(mark));
while (b != d && !mark[b])
{
mark[b] = true;
go();
ans++;
blen++;
}
if (mark[b])
{
cout << -1 << endl;
return 0;
}
if (a == c)
{
cout << ans << endl;
return 0;
}
int pos = 0;
while (a != c)
{
a = nexta[a];
pos++;
}
pos = alen - pos;
memset(mark, false, sizeof(mark));
while (pos != 0 && !mark[pos])
{
mark[pos] = true;
pos = (pos + blen) % alen;
ans += blen;
}
if (mark[pos])
cout << -1 << endl;
else
cout << ans << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y3N0cmluZz4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKY29uc3QgaW50IE1BWCA9IDEwMDAwMDU7CmludCBwLCBhLCBiLCBjLCBkLCB4YSwgeWEsIHhiLCB5YjsKaW50IG5leHRhW01BWF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