#include <bits/stdc++.h>
using namespace std;
const long long maxn = 2e6 + 107;
long long m;
long long h[2], x[2], y[2], a[2];
long long l = 0, r = 0, X = -1, Y = -1;
vector<long long> K, T;
vector<long long> q, w;
int s[maxn];
map<long long, long long> F, G;
long long c1, c2;
int main() {
  cin >> m;
  cin >> h[0] >> a[0];
  cin >> x[0] >> y[0];
  cin >> h[1] >> a[1];
  cin >> x[1] >> y[1];
  memset(s, 0, sizeof(s));
  s[h[0]] = 1;
  q.push_back(h[0]);
  while (1) {
    long long k = h[0];
    k = k * x[0] % m;
    h[0] = (k + y[0]) % m;
    if (s[h[0]] == 0) {
      ++l;
      q.push_back(h[0]);
      s[h[0]] = 1;
      if (h[0] == a[0]) {
        X = l;
      }
    } else
      break;
  }
  for (int i = 0;; i++)
    if (q[i] == h[0]) {
      c1 = i;
      break;
    }
  memset(s, 0, sizeof(s));
  s[h[1]] = 1;
  w.push_back(h[1]);
  while (1) {
    long long k = h[1];
    k = k * x[1] % m;
    h[1] = (k + y[1]) % m;
    if (s[h[1]] == 0) {
      ++r;
      w.push_back(h[1]);
      s[h[1]] = 1;
      if (h[1] == a[1]) {
        Y = r;
      }
    } else
      break;
  }
  for (int i = 0;; i++)
    if (w[i] == h[1]) {
      c2 = i;
      break;
    }
  if (X == -1 || Y == -1) {
    cout << -1;
    return 0;
  }
  long long k1, k2, ans = -1;
  if (X == Y)
    ans = X;
  else {
    if (X < c1 && Y < c2)
      ans = -1;
    else if (X < c1) {
      if (X > Y && (X - Y) % (r - c2 + 1) == 0)
        ans = X;
      else
        ans = -1;
    } else if (Y < c2) {
      if (Y > X && (Y - X) % (l - c1 + 1) == 0)
        ans = Y;
      else
        ans = -1;
    } else {
      l = l - c1 + 1;
      r = r - c2 + 1;
      if (r > 1) {
        for (k1 = 0; k1 < 1e6; k1++)
          if ((k1 * l + X - Y) % r == 0) {
            ans = k1 * l + X;
            break;
          }
      } else if (l > 1) {
        for (k2 = 0; k2 < 1e6; k2++)
          if ((k2 * r + Y - X) % l == 0) {
            ans = k2 * r + Y;
            break;
          }
      } else {
        ans = max(X, Y);
      }
    }
  }
  cout << ans;
  return 0;
}
