#include <bits/stdc++.h>
using namespace std;
int mod1 = int(1e9) + 7;
int ins[1000000];
bool after[1000000];
vector<int> solve(long long m, long long h, long long a, long long x,
                  long long y) {
  memset(ins, -1, sizeof(ins));
  memset(after, false, sizeof(false));
  int t, r, f, cl;
  t = r = f = cl = 0;
  bool af = false, afb;
  ins[h] = 0;
  while (true) {
    h = (x * h + y) % m;
    cl++;
    afb = af;
    if (!af) t++;
    if (h == a) {
      af = true;
    }
    if (ins[h] >= 0) {
      if (!af) {
        return vector<int>{-1};
      } else {
        r = cl - ins[h];
        if (after[h]) f = true;
        break;
      }
    }
    ins[h] = cl;
    if (afb) after[h] = true;
  }
  return vector<int>{t, r, f};
}
int main() {
  long long m, h1, h2, a1, a2, x1, x2, y1, y2;
  bool f1, f2;
  cin >> m;
  cin >> h1 >> a1 >> x1 >> y1;
  cin >> h2 >> a2 >> x2 >> y2;
  long long t1, t2, r1, r2;
  vector<int> v1 = solve(m, h1, a1, x1, y1);
  vector<int> v2 = solve(m, h2, a2, x2, y2);
  if (v1[0] == -1 || v2[0] == -1) {
    cout << -1 << endl;
    return 0;
  }
  t1 = v1[0];
  r1 = v1[1];
  f1 = v1[2];
  t2 = v2[0];
  r2 = v2[1];
  f2 = v2[2];
  if (f1 && f2) {
    cout << (t1 == t2 ? t1 : -1) << endl;
    return 0;
  }
  if (f1 && !f2) {
    cout << (t1 >= t2 && (t1 - t2) % r2 == 0 ? t1 : -1) << endl;
    return 0;
  }
  if (!f1 && f2) {
    cout << (t2 >= t1 && (t2 - t1) % r1 == 0 ? t2 : -1) << endl;
    return 0;
  }
  long long h, y, mm;
  h = max(t1, t2) - min(t1, t2);
  if (t1 > t2) {
    y = r1;
    mm = r2;
  } else {
    y = r2;
    mm = r1;
  }
  set<long long> s;
  long long tt = 0;
  s.insert(h);
  while (h % mm != 0) {
    h = (h + y) % mm;
    tt++;
    if (s.find(h) != s.end()) {
      cout << -1 << endl;
      return 0;
    }
    s.insert(h);
  }
  cout << (max(t1, t2) + y * tt) << endl;
  return 0;
}
