#include <bits/stdc++.h>
using namespace std;
int T = 1;
long long m, h[2], a[2], x[2], y[2];
long long find(long long h, long long x, long long y, long long a) {
  for (int c = 0;;) {
    h = (h * x + y) % m;
    ++c;
    if (h == a) return c;
    if (c > m) return -1;
  }
}
int main() {
  while (T--) {
    cin >> m;
    cin >> h[0] >> a[0] >> x[0] >> y[0];
    cin >> h[1] >> a[1] >> x[1] >> y[1];
    long long p[2], q[2];
    p[0] = find(h[0], x[0], y[0], a[0]);
    p[1] = find(a[0], x[0], y[0], a[0]);
    q[0] = find(h[1], x[1], y[1], a[1]);
    q[1] = find(a[1], x[1], y[1], a[1]);
    if (p[0] == -1 || q[0] == -1) {
      cout << -1 << endl;
      continue;
    }
    long long ans = -1, up = int(1e7);
    for (long long t = 0; t <= up && ans == -1; ++t) {
      if (p[1] == -1 && t != 0) continue;
      long long _L = p[0] + p[1] * t;
      long long L = _L - q[0];
      if (L < 0) continue;
      if (q[1] == -1 && L != 0) continue;
      if (L % q[1] != 0) continue;
      ans = _L;
    }
    cout << ans << endl;
  }
  return 0;
}
