#include <bits/stdc++.h>
using namespace std;
int m, x[3], y[3], h[3], a[3], d[3], p[2][1000010], st[3], fir[3];
int po[1000010], id, idx;
long long xx, ans;
int main() {
  scanf("%d", &m);
  for (int i = 0; i < 2; i++) {
    scanf("%d%d", &h[i], &a[i]);
    scanf("%d%d", &x[i], &y[i]);
  }
  for (int i = 0; i < 2; i++) {
    p[i][0] = h[i];
    memset(po, -1, sizeof po);
    po[h[i]] = 0;
    for (int j = 1; j <= m; j++) {
      p[i][j] = (1ll * p[i][j - 1] * x[i] + y[i]) % m;
      if (po[p[i][j]] == -1)
        po[p[i][j]] = j;
      else {
        d[i] = j - po[p[i][j]];
        st[i] = po[p[i][j]];
        break;
      }
    }
  }
  for (int i = 0; i < 2; i++) {
    for (int j = 1; j <= m; j++)
      p[i][j] = (1ll * p[i][j - 1] * x[i] + y[i]) % m;
  }
  fir[0] = fir[1] = -1;
  for (int i = 0; i < 2; i++) {
    for (int j = 0; j <= m; j++)
      if (p[i][j] == a[i]) {
        fir[i] = j;
        break;
      }
  }
  if (fir[0] == -1 || fir[1] == -1) {
    puts("-1");
    return 0;
  }
  if (fir[0] < st[0]) {
    if (p[1][fir[0]] == a[1]) {
      printf("%d", fir[0]);
      return 0;
    } else {
      puts("-1");
      return 0;
    }
  }
  if (fir[1] < st[1]) {
    if (p[0][fir[1]] == a[0]) {
      printf("%d", fir[1]);
      return 0;
    } else {
      puts("-1");
      return 0;
    }
  }
  ans = -1;
  id = 1;
  if (fir[1] > fir[0]) id = 0;
  idx ^= id ^ 1;
  for (int step = 0; step <= d[id]; step++) {
    xx = 1ll * step * d[idx] + fir[idx];
    if ((xx - fir[id]) % d[id] == 0) {
      ans = xx;
      break;
    }
  }
  printf("%I64d\n", ans);
}
