#include <bits/stdc++.h>
const int N = 1000010;
int m, mp[N];
struct Gao {
  int h, a, x, y, p, q;
  void in() { scanf("%d%d%d%d", &h, &a, &x, &y); }
  int cal(long long A, long long B) {
    memset(mp, -1, sizeof(mp));
    for (int i = 1;; i++) {
      A = (A * x + y) % m;
      if (A == B) {
        return i;
      }
      if (mp[A] != -1) {
        return -1;
      }
      mp[A] = i;
    }
  }
  void solve() {
    p = cal(h, a);
    q = cal(a, a);
  }
} a, b;
int gcd(int x, int y) { return !y ? x : gcd(y, x % y); }
long long solve() {
  if (a.p == -1 || b.p == -1) {
    return -1;
  }
  if (a.p == b.p) {
    return a.p;
  }
  if (a.p < b.p) {
    std::swap(a, b);
  }
  if (b.q != -1 && (a.p - b.p) % b.q == 0) {
    return a.p;
  }
  if (a.q == -1 || b.q == -1) return -1;
  int g = gcd(a.q, b.q);
  if ((a.p - b.p) % g != 0) {
    return -1;
  }
  if (a.q < b.q) {
    std::swap(a, b);
  }
  for (int i = 1; i <= m; i++) {
    long long tmp = (long long)i * a.q + a.p;
    if (tmp >= b.p && (tmp - b.p) % b.q == 0) {
      return tmp;
    }
  }
  return -1;
}
int main() {
  scanf("%d", &m);
  a.in();
  b.in();
  a.solve();
  b.solve();
  printf("%I64d\n", solve());
}
