#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))
#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))
#define rep(i, c) for(auto &(i) : (c))
#define x first
#define y second
#define pb push_back
#define PB pop_back()
#define iOS ios_base::sync_with_stdio(false)
#define sqr(a) (((a) * (a)))
#define all(a) a.begin() , a.end()
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n";
#define coud(a,b) cout<<fixed << setprecision((b)) << (a)
#define L(x) ((x)<<1)
#define R(x) (((x)<<1)+1)
#define umap unordered_map
#define double long double
typedef long long ll;
typedef pair<int,int>pii;
typedef vector<int> vi;
typedef complex<double> point;
template <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T>  inline void smax(T &x,T y){ x = max((x), (y));}
template <class T>  inline void smin(T &x,T y){ x = min((x), (y));}
int a[2], b[2], x[3], y[3], p;
inline int nex(int c, int w){
	return (1LL * c * x[w] + y[w])%p;
}
int main(){
	iOS;
	cin >> p;
	For(i,0,2){
		if(!i)
			cin >> a[0] >> a[1];
		else
			cin >> b[0] >> b[1];
		cin >> x[i] >> y[i];
	}
	ll ans = 0LL;
	while(a[0] != a[1] && ans < p + 20){
		++ ans;
		a[0] = nex(a[0], 0);
		b[0] = nex(b[0], 1);
	}
	if(a[0] != a[1]){
		cout << -1 << endl;
		return 0;
	}
	if(a[0] == a[1] && b[0] == b[1]){
		cout << ans << endl;
		return 0;
	}
	int o = 0;
	int cur = a[0];
	x[2] = x[1], y[2] = y[1];
	x[1] = 1, y[1] = 0;
	do{
		cur = nex(cur, 0);
		++ o;
		x[1] = (1LL * x[1] * x[2]) % p;
		y[1] = (1LL * y[1] * x[2]) % p;
		y[1] = (1LL * y[1] + y[2]) % p;
	}while(o < p + 10 && cur != a[1]);
	if(cur != a[1]){
		cout << -1 << endl;
		return 0;
	}
	int O = 0;
	cur = b[0];
	do{
		cur = nex(cur, 1);
		++ O;
	}while(O < p + 10 && cur != b[1]);
	if(cur != b[1]){
		cout << -1 << endl;
		return 0;
	}
	ans += 1LL * o * O;
	cout << ans << endl;
}

