#include <bits/stdc++.h>
using namespace std;
void period(int m, long long h, long long x, long long y, int *P, int *N,
            int &pad, int &len) {
  fill(P, P + 1000010, -1);
  fill(N, N + 1000010, -1);
  int p = 0;
  do {
    P[p] = h;
    N[h] = p;
    h = (x * h + y) % m;
    p++;
  } while (N[h] == -1);
  len = p - N[h];
  pad = p - len;
}
int getPos(long long t, int len, int pad) {
  if (t < pad + len) {
    return t;
  } else {
    return (t - pad) % len + pad;
  }
}
int main() {
  int m;
  while (cin >> m) {
    int h1, a1, x1, y1;
    cin >> h1 >> a1 >> x1 >> y1;
    int h2, a2, x2, y2;
    cin >> h2 >> a2 >> x2 >> y2;
    static int N1[1000010], N2[1000010];
    static int P1[1000010], P2[1000010];
    int pad1, len1;
    int pad2, len2;
    period(m, h1, x1, y1, P1, N1, pad1, len1);
    period(m, h2, x2, y2, P2, N2, pad2, len2);
    if (N1[a1] == -1 || N2[a2] == -1) {
      cout << -1 << endl;
    } else {
      bool answer = false;
      long long t = 0;
      for (; t < max(pad1 + len1, pad2 + len2); t++) {
        if (P1[getPos(t, len1, pad1)] == a1 &&
            P2[getPos(t, len2, pad2)] == a2) {
          answer = true;
          break;
        }
      }
      if (!answer) {
        t = max(N1[a1], N2[a2]);
        int iter = 0;
        answer = true;
        while (P1[getPos(t, len1, pad1)] != a1 ||
               P2[getPos(t, len2, pad2)] != a2) {
          t += (N1[a1] > N2[a2]) ? len1 : len2;
          iter++;
          if (iter > max(len1, len2)) {
            answer = false;
            break;
          }
        }
      }
      cout << (answer ? t : -1) << endl;
    }
  }
  return 0;
}
