#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
long long MIN(long long a, long long b) {
  if (a > b) return b;
  return a;
}
int main() {
  long long H1, H2;
  long long m, h1, a1, x1, y1;
  long long h2, a2, x2, y2;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  H1 = h1;
  H2 = h2;
  long long ans1 = 1;
  for (; ans1 <= m + 1; ans1++) {
    h1 = x1 * h1 + y1;
    h1 %= m;
    if (h1 == a1) {
      break;
    }
  }
  long long ans2 = 1;
  for (; ans2 <= m + 1; ans2++) {
    h2 = x2 * h2 + y2;
    h2 %= m;
    if (h2 == a2) {
      break;
    }
  }
  long long cyc1 = 1;
  for (; cyc1 <= m + 1; cyc1++) {
    h1 = x1 * h1 + y1;
    h1 %= m;
    if (h1 == a1) {
      break;
    }
  }
  long long cyc2 = 1;
  for (; cyc2 <= m + 1; cyc2++) {
    h2 = x2 * h2 + y2;
    h2 %= m;
    if (h2 == a2) {
      break;
    }
  }
  bool ok = 1;
  if (ans1 > m + 1 || ans2 > m + 1) ok = 0;
  if (ok) {
    if (cyc1 > m + 1) cyc1 = 0;
    if (cyc2 > m + 1) cyc2 = 0;
    set<long long> s;
    for (int i = 0; i <= m; i++) {
      s.insert(ans1 + cyc1 * i);
    }
    for (int i = 0; i <= m; i++) {
      if (s.count(ans2 + cyc2 * i)) {
        cout << ans2 + cyc2 * i << endl;
        return 0;
      }
    }
    cout << -1;
  } else {
    cout << -1;
  }
  return 0;
}
