#include <bits/stdc++.h>
using namespace std;
long long mdl;
vector<long long> vis;
void gen(long long& f, long long& p, long long h, long long a, long long x,
         long long y) {
  vis = vector<long long>(1000009, -1);
  long long ct = 0;
  while (vis[h] == -1) {
    vis[h] = ct;
    h = (x * h + y) % mdl;
    ++ct;
  }
  if (vis[a] == -1) {
    cout << -1 << endl;
    exit(0);
  }
  f = vis[a];
  p = ct - vis[h];
  if (vis[a] < vis[h]) p = -1;
}
long long f1, p1, f2, p2;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> mdl;
  long long h1, a1, x1, y1;
  cin >> h1 >> a1 >> x1 >> y1;
  gen(f1, p1, h1, a1, x1, y1);
  cin >> h1 >> a1 >> x1 >> y1;
  gen(f2, p2, h1, a1, x1, y1);
  long long c1 = f1;
  long long rth = f1 % p2;
  long long trs = 0;
  long long r2 = f2 % p2;
  long long radd = p1 % p2;
  if (p2 == -1) {
    swap(f1, f2);
    swap(p1, p2);
  }
  if (p1 == -1) {
    if (p2 == -1) {
      if (f1 == f2)
        cout << f1 << endl;
      else
        cout << -1 << endl;
      return 0;
    }
    if (f1 >= f2 && (f1 - f2) % p2 == f2 % p2)
      cout << f1 << endl;
    else
      cout << -1 << endl;
    return 0;
  }
  while (trs < 2000009 && (c1 < f2 || rth != r2)) {
    ++trs;
    c1 += p1;
    rth += radd;
    if (rth >= p2) rth -= p2;
  }
  if (c1 >= f2 && rth == r2)
    cout << c1 << endl;
  else
    cout << -1 << endl;
  return 0;
}
