#include <bits/stdc++.h>
using namespace std;
long long m, h1, a1, x1, y11, h2, a2, x2, y2;
long long b1, c1, b2, c2;
long long tinh(long long h, long long a, long long x, long long y) {
  long long dem = 0;
  while (dem <= 2 * m) {
    h = (x * h + y) % m;
    dem++;
    if (h == a) return dem;
  }
  return 0;
}
int main() {
  cin >> m >> h1 >> a1 >> x1 >> y11 >> h2 >> a2 >> x2 >> y2;
  b1 = tinh(h1, a1, x1, y11);
  b2 = tinh(h2, a2, x2, y2);
  c1 = tinh(a1, a1, x1, y11);
  c2 = tinh(a2, a2, x2, y2);
  if (b1 == 0 || b2 == 0) {
    cout << "-1";
    return 0;
  } else if (b1 == b2) {
    cout << b1;
    return 0;
  } else {
    for (long long i = 0; i < max(c1, c2); i++) {
      long long tg = b1 + i * c1;
      if (tg > b2 && c2 > 0 && (tg - b2) % c2 == 0) {
        cout << tg;
        return 0;
      }
      long long tt = b2 + i * c2;
      if (tt > b1 && c1 > 0 && (tt - b1) % c1 == 0) {
        cout << tt;
        return 0;
      }
    }
  }
  cout << "-1";
  return 0;
}
