#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;
}
