#include <bits/stdc++.h>
using namespace std;
const int MAXM = 1e6 + 10;
long long m, h[2], a[2], x[2], y[2], nxt[3][MAXM];
long long ans;
bool bf(int n) {
  while (n-- > 0) {
    if (h[0] == a[0] && h[1] == a[1]) return true;
    for (int k = 0; k < 2; k++) h[k] = (x[k] * h[k] + y[k]) % m;
    ans++;
  }
  return h[0] == a[0] && h[1] == a[1];
}
pair<long long, long long> getAB(long long h, long long a, long long x,
                                 long long y, long long nxt[MAXM]) {
  long long ra, rb, t;
  ra = rb = 0;
  t = h;
  while (nxt[t] == -1) {
    t = nxt[t] = (t * x + y) % m;
    ra++;
  }
  for (rb = 0; h != a && rb < 2 * m; rb++) h = nxt[h];
  if (rb == 2 * m) return make_pair(0, -1);
  return make_pair(ra, rb);
}
int main() {
  cin >> m;
  for (int i = 0; i < 2; i++) cin >> h[i] >> a[i] >> x[i] >> y[i];
  ans = 0;
  if (!bf(m << 1)) {
    pair<long long, long long> p[2];
    memset(nxt, -1, sizeof(nxt));
    for (int i = 0; i < 2; i++) p[i] = getAB(h[i], a[i], x[i], y[i], nxt[i]);
    int u = 0, v = 1;
    if (p[u].second > p[v].second) u = 1, v = 0;
    for (int i = 0; i < p[u].second; i++)
      for (int k = 0; k < 2; k++) h[k] = nxt[k][h[k]];
    ans += p[u].second;
    long long t = h[v], s = h[v];
    for (int i = 0; i < p[u].first; i++) t = nxt[v][t];
    while (nxt[2][s] == -1) {
      nxt[2][s] = t;
      t = nxt[v][t];
      s = nxt[v][s];
    }
    for (int i = 0; i < 2 * m && h[v] != a[v]; i++) {
      h[v] = nxt[2][h[v]];
      ans += p[u].first;
    }
  }
  if (h[0] == a[0] && h[1] == a[1])
    cout << ans;
  else
    cout << -1;
  return 0;
}
