#include <bits/stdc++.h>
using namespace std;
int a[1000005];
int main() {
  int h1, x1, y1, a1, m;
  int u1, v1, w1, u2, v2, w2;
  int h2, x2, y2, a2;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  memset(a, -1, sizeof(a));
  a[h1] = 0;
  u1 = -1;
  for (int i = 1; 1; i++) {
    int w = ((long long)h1 * x1) % m + y1;
    w %= m;
    if (a[w] != -1) {
      v1 = a[w];
      w1 = i;
      break;
    } else {
      a[w] = i;
      h1 = w;
    }
    if (w == a1) {
      u1 = i;
    }
  }
  memset(a, -1, sizeof(a));
  u2 = -1;
  for (int i = 1; 1; i++) {
    int w = ((long long)h2 * x2) % m + y2;
    w %= m;
    if (a[w] != -1) {
      v2 = a[w];
      w2 = i;
      break;
    } else {
      a[w] = i;
      h2 = w;
    }
    if (w == a2) u2 = i;
  }
  if (u1 == -1 || u2 == -1)
    printf("-1\n");
  else {
    if (u1 == u2) {
      printf("%d\n", u1);
    } else {
      if (u1 < v1) {
        if (u2 < v2) {
          printf("-1\n");
        } else {
          if (u1 >= u2 && (u1 - u2) % (w2 - v2) == 0) {
            printf("%d\n", u1);
          } else
            printf("-1\n");
        }
      } else {
        if (u2 < v2) {
          if (u2 >= u1 && (u2 - u1) % (w1 - v1) == 0) {
            printf("%d\n", u2);
          } else
            printf("-1\n");
        } else {
          w1 = w1 - v1;
          w2 = w2 - v2;
          int f = 0;
          long long ff = 0;
          if (u1 <= u2) {
            for (int i = 0; i <= w1; i++) {
              if (((u2 - u1) + (long long)i * (w2)) % w1 == 0) {
                f = 1;
                ff = (long long)i * w2 + u2;
                break;
              }
            }
          } else {
            for (int i = 0; i <= w2; i++) {
              if (((u1 - u2) + (long long)i * w1) % w2 == 0) {
                f = 1;
                ff = (long long)i * w1 + u1;
                break;
              }
            }
          }
          if (f)
            cout << ff << endl;
          else
            printf("-1\n");
        }
      }
    }
  }
}
