#include <bits/stdc++.h>
using namespace std;
int countBits(long long mask) {
  int res = 0;
  while (mask) mask &= (mask - 1), ++res;
  return res;
}
string toString(long long n) {
  stringstream ss;
  ss << n;
  return ss.str();
}
long long toNumber(string s) {
  stringstream ss;
  long long n;
  ss << s;
  ss >> n;
  return n;
}
long long steps(long long a, long long x, long long y, long long h, long long m,
                bool skip) {
  unordered_map<long long, bool> tmp;
  long long s = 0;
  while (skip || h != a) {
    if (tmp[h]) return -1;
    tmp[h] = true;
    h = (x * h + y) % m;
    s++;
    skip = false;
  }
  return s;
}
int main() {
  long long m, h1, h2, x1, x2, y1, y2, a1, a2;
  while (cin >> m >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2) {
    long long b = steps(a1, x1, y1, h1, m, false);
    long long c = steps(a2, x2, y2, h2, m, false);
    if (b == -1 || c == -1) {
      cout << -1 << endl;
      continue;
    }
    if (b == c) {
      cout << b << endl;
      continue;
    }
    long long c1 = steps(a1, x1, y1, a1, m, true);
    long long c2 = steps(a2, x2, y2, a2, m, true);
    if (c1 == c2 && c1 == -1) {
      cout << -1 << endl;
      continue;
    }
    if (c2 == -1) {
      swap(c1, c2);
      swap(b, c);
    }
    if (c1 == -1) c1 = 0;
    if (c2 == -1) c2 = 0;
    long long res = LLONG_MAX;
    for (int x = (int)(0), _m = (int)(1000000); x < _m; ++x) {
      long long y = b + c1 * x - c;
      if (y >= 0 && y % c2 == 0) res = min(res, b + c1 * x);
    }
    if (res == LLONG_MAX) res = -1;
    cout << res << endl;
  }
}
