#include <bits/stdc++.h>
using namespace std;
int h[3], t[3], d[3], x[3], y[3], a[3];
int b[1000005], c[1000005], bb[1000005], cc[1000005];
int sb, sc, tb, tc;
long long ans, e, f;
int main() {
  int i, j, k;
  int m, bc;
  scanf("%d", &m);
  scanf("%d %d", b + 1, a + 1);
  scanf("%d %d", x + 1, y + 1);
  scanf("%d %d", c + 1, a + 2);
  scanf("%d %d", x + 2, y + 2);
  bb[b[1]] = 1;
  cc[c[1]] = 1;
  sb = 1;
  sc = 1;
  while (1) {
    sb++;
    b[sb] = (1ll * b[sb - 1] * x[1] + y[1]) % m;
    if (bb[b[sb]]) {
      t[1] = sb - bb[b[sb]];
      break;
    }
    bb[b[sb]] = sb;
  }
  while (1) {
    sc++;
    c[sc] = (1ll * c[sc - 1] * x[2] + y[2]) % m;
    if (cc[c[sc]]) {
      t[2] = sc - cc[c[sc]];
      break;
    }
    cc[c[sc]] = sc;
  }
  bc = max(sb, sc);
  tb = sb - t[1], tc = sc - t[2];
  for (i = 1; i < bc; i++) {
    if (i > tb)
      j = (i - tb) % t[1] + tb;
    else
      j = i;
    if (i > tc)
      k = (i - tc) % t[2] + tc;
    else
      k = i;
    if (b[j] == a[1] && c[k] == a[2]) break;
  }
  if (i < bc)
    printf("%d", i - 1);
  else {
    for (i = tb; i < sb; i++)
      if (b[i] == a[1]) break;
    if (i == sb)
      puts("-1");
    else {
      d[1] = i;
      for (i = tc; i < sc; i++)
        if (c[i] == a[2]) break;
      if (i == sc)
        puts("-1");
      else {
        d[2] = i;
        if (d[1] >= d[2])
          j = 0;
        else
          j = (d[2] - d[1] + 1) / t[1];
        for (i = 0; i < t[2]; i++) {
          e = d[1] + 1ll * t[1] * j - d[2];
          if (e % t[2] == 0) break;
          j++;
        }
        if (i == t[2])
          puts("-1");
        else {
          ans = d[1] + 1ll * t[1] * j;
          printf("%I64d", ans - 1);
        }
      }
    }
  }
}
