#include <bits/stdc++.h>
using namespace std;
const int M = 1000007;
int a[M], b[M], m;
void solve(int x, int y, long long h, int *p, int &bg, int &len) {
  memset(p, 0, M * (sizeof p[0]));
  int cnt = 0;
  while (p[h] == 0) {
    p[h] = ++cnt;
    h = (x * h + y) % m;
  }
  bg = p[h];
  len = cnt + 1 - bg;
}
int main() {
  int x1, x2, y1, y2, h1, h2, z1, z2, bg1, bg2, len1, len2;
  scanf("%d%d%d%d%d%d%d%d%d", &m, &h1, &z1, &x1, &y1, &h2, &z2, &x2, &y2);
  solve(x1, y1, h1, a, bg1, len1);
  solve(x2, y2, h2, b, bg2, len2);
  if (a[z1] > 0 && b[z2] > 0) {
    if (a[z1] < bg1) {
      if (b[z2] < bg2)
        printf("%d\n", a[z1] == b[z2] ? a[z1] - 1 : -1);
      else
        printf("%d\n", ((a[z1] - b[z2]) % len2 == 0 && a[z1] >= b[z2])
                           ? a[z1] - 1
                           : -1);
    } else {
      if (b[z2] < bg2)
        printf("%d\n", ((b[z2] - a[z1]) % len1 == 0 && a[z1] <= b[z2])
                           ? b[z2] - 1
                           : -1);
      else {
        long long t1 = a[z1], t2 = b[z2];
        while (t1 != t2) {
          if (t1 < t2)
            t1 += (t2 - t1 + len1 - 1) / len1 * len1;
          else
            t2 += (t1 - t2 + len2 - 1) / len2 * len2;
          if (t1 > 2LL * len1 * len2) break;
        }
        cout << ((t1 != t2) ? -1 : t1 - 1) << endl;
      }
    }
  } else
    puts("-1");
  return 0;
}
