#include <bits/stdc++.h>
using namespace std;
int main() {
  long long m;
  long long h[2], a[2];
  long long x[2], y[2];
  cin >> m;
  for (int i = 0; i < 2; ++i) cin >> h[i] >> a[i] >> x[i] >> y[i];
  long long w[2], b[2];
  for (int i = 0; i < 2; ++i) {
    w[i] = 0;
    b[i] = 0;
    long long f = h[i];
    do {
      f = (x[i] * f + y[i]) % m;
      ++w[i];
      if (f == a[i]) {
        if (!b[i])
          b[i] = w[i];
        else {
          w[i] = w[i] - b[i];
          break;
        }
      }
    } while (f != h[i] && w[i] <= m);
    if (!b[i]) {
      cout << "-1\n";
      return 0;
    }
  }
  long long k[2] = {0, 0};
  long long z[2] = {b[0], b[1]};
  long long d = z[0] - z[1];
  long long d0 = d;
  while (d) {
    if (d < 0) {
      if (w[0] <= m)
        ++k[0];
      else
        break;
    }
    if (d > 0) {
      if (w[1] <= m)
        ++k[1];
      else
        break;
    }
    for (int i = 0; i < 2; ++i) z[i] = b[i] + k[i] * w[i];
    d = z[0] - z[1];
    if (d == d0) break;
  }
  if (d)
    cout << "-1\n";
  else
    cout << z[0] << endl;
}
