#include <bits/stdc++.h>
using namespace std;
pair<long long, long long> solve(long long m, long long h, long long x,
                                 long long y, long long a) {
  vector<long long> memo(m, 0);
  long long p = 0;
  long long q = -1;
  long long cnt = 0;
  while (true) {
    if (memo[h] > 3) break;
    if (memo[h] == 0 && h == a) {
      q = cnt;
    } else if (memo[h] == 1 && h == a) {
      p = cnt - q;
      break;
    }
    memo[h]++;
    cnt++;
    h = (h * x + y) % m;
  }
  return make_pair(p, q);
}
int main() {
  long long m, h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  pair<long long, long long> res1 = solve(m, h1, x1, y1, a1);
  pair<long long, long long> res2 = solve(m, h2, x2, y2, a2);
  if (res1.second < 0 || res2.second < 0) {
    cout << -1 << endl;
    return 0;
  }
  long long a = res1.first;
  long long b = res1.second;
  long long c = res2.first;
  long long d = res2.second;
  if (a == 0) {
    if (c == 0) {
      if (b == d) {
        cout << b << endl;
        return 0;
      }
    } else {
      if (b >= d && (b - d) % c == 0) {
        cout << b << endl;
        return 0;
      }
    }
  } else if (c == 0) {
    if (a == 0) {
      if (b == d) {
        cout << b << endl;
        return 0;
      }
    } else {
      if (d >= b && (d - b) % a == 0) {
        cout << d << endl;
        return 0;
      }
    }
  } else {
    long long j = 0;
    long long cnt = a;
    while (cnt >= 0) {
      if (c * j + d - b >= 0) {
        if ((c * j + d - b) % a == 0) {
          cout << (c * j + d) << endl;
          return 0;
        }
        cnt--;
      }
      j++;
    }
  }
  cout << -1 << endl;
  return 0;
}
