#include <bits/stdc++.h>
using namespace std;
using LL = long long;
LL m;
LL iter(LL h, LL a, LL x, LL y) {
  LL r = 0;
  while (h != a) {
    h = (x * h + y) % m;
    if (++r > m) return -1;
  }
  return r;
}
int main() {
  LL c[2], p[2];
  cin >> m;
  for (int i = 0; i < (2); i++) {
    LL h, a, x, y;
    cin >> h >> a >> x >> y;
    c[i] = iter(h, a, x, y);
    p[i] = iter((x * a + y) % m, a, x, y) + 1;
  }
  if (((!~*c || !~c[1]) && cout << "-1\n") ||
      (*c == c[1] && cout << *c << '\n') || (!*p && !p[1] && cout << "-1\n"))
    return 0;
  if (!*p) swap(*c, c[1]), swap(*p, p[1]);
  for (int x = 0; x < (m); x++) {
    LL t = *p * x + *c;
    if (t >= c[1] && (p[1] || t == c[1]) && (!p[1] || !((t - c[1]) % p[1]))) {
      cout << t << '\n';
      return 0;
    }
  }
  cout << "-1\n";
}
