#include <bits/stdc++.h>
using namespace std;
bool seen[1000000];
int m;
long long X[2], M[2];
long long findPos(long long s, long long t, int x, int y) {
  memset(seen, 0, sizeof seen);
  int q = 0;
  do {
    seen[s] = true;
    s = (x * s + y) % m;
    ++q;
  } while (not seen[s] and s != t);
  return s == t ? q : -1;
}
long long extGcd(long long a, long long b, long long &x, long long &y) {
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  }
  long long xp, g = extGcd(b, a % b, xp, x);
  y = xp - a / b * x;
  return g;
}
long long solve() {
  if (X[0] == -1 or X[1] == -1) return -1;
  if (M[0] == -1 and M[1] == -1) return X[0] == X[1] ? X[0] : -1;
  if (M[0] == -1)
    return X[0] % M[1] == X[1] % M[1] and X[0] >= X[1] ? X[0] : -1;
  if (M[1] == -1)
    return X[1] % M[0] == X[0] % M[0] and X[1] >= X[0] ? X[1] : -1;
  long long Y[2];
  long long g = extGcd(M[0], M[1], Y[0], Y[1]);
  if (abs(X[0] - X[1]) % g) return -1;
  long long mod = (M[0] * M[1]) / g,
            ans = (X[0] * M[1] * Y[1] / g + X[1] * M[0] * Y[0] / g) % mod;
  while (ans < X[0] or ans < X[1]) ans += mod;
  return ans;
}
int main() {
  ios::sync_with_stdio(false);
  cin >> m;
  for (int i = 0; i < 2; ++i) {
    int h, a, x, y;
    cin >> h >> a >> x >> y;
    X[i] = findPos(h, a, x, y);
    M[i] = findPos(a, a, x, y);
  }
  cout << solve() << endl;
  return 0;
}
