#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  gcd(b, a % b);
}
long long extendedEuclid(long long a, long long b, long long c) {
  long long x1 = 1, y1 = 0, x2 = 0, y2 = 1;
  while (b) {
    long long r = a % b;
    long long x = x2, y = y2;
    x2 = x1 - (a / b) * x2;
    y2 = y1 - (a / b) * y2;
    x1 = x, y1 = y;
    a = b;
    b = r;
  }
  return x1;
}
long long m, h1, h2, a1, a2, x11, x22, y11, y22;
int main() {
  cin >> m;
  cin >> h1 >> a1 >> x11 >> y11 >> h2 >> a2 >> x22 >> y22;
  long long res1 = h1, res2 = h2, pos1, pos2;
  bool ok1 = 0, ok2 = 0;
  long long period1 = -1, period2 = -1;
  for (long long i = 1; i <= 2 * m; i++) {
    res1 = (res1 * x11 + y11) % m;
    res2 = (res2 * x22 + y22) % m;
    if (period1 == -1 && ok1 == 1 && res1 == a1) period1 = i - pos1;
    if (period2 == -1 && ok2 == 1 && res2 == a2) period2 = i - pos2;
    if (ok1 == 0 && res1 == a1) {
      ok1 = 1;
      pos1 = i;
    }
    if (ok2 == 0 && res2 == a2) {
      ok2 = 1;
      pos2 = i;
    }
    if (res1 == a1 && res2 == a2) {
      cout << i << '\n';
      return 0;
    }
  }
  if (ok1 && ok2) {
    if (period1 != -1 && period2 != -1) {
      long long g = gcd(period1, period2);
      if (pos1 % g == pos2 % g) {
        long long m = period1 * period2;
        long long x1 =
            ((extendedEuclid(period2 % period1, period1, 1) + period1) %
             period1) *
            pos1 % period1;
        long long x2 =
            ((extendedEuclid(period1 % period2, period2, 1) + period2) %
             period2) *
            pos2 % period2;
        cout << (period2 * x1 % m + period1 * x2 % m) % m << '\n';
      } else
        cout << -1 << '\n';
      return 0;
    }
    cout << -1 << '\n';
    return 0;
  }
  cout << -1 << '\n';
  return 0;
}
