#include <bits/stdc++.h>
using namespace std;
void read_file(bool outToFile = true) { ios::sync_with_stdio(false); }
int m, h1, x1, y11, a1, h2, x2, y22, a2;
int x, y;
void build(int c) {
  x = 1;
  y = 0;
  for (int i = 1; i <= c; i++) {
    y = (0LL + y + x) % m;
    x = (1LL * x * x2) % m;
  }
}
int f(int v) { return ((1LL * x * v) % m + (1LL * y22 * y) % m) % m; }
int main() {
  read_file(false);
  while (cin >> m) {
    cin >> h1 >> a1 >> x1 >> y11;
    cin >> h2 >> a2 >> x2 >> y22;
    int u = h1;
    int q = 0;
    for (int i = 1; i <= m && !q; i++) {
      u = (1LL * x1 * u) % m + y11, u %= m;
      if (u == a1) q = i;
    }
    if (!q) {
      cout << -1 << endl;
      continue;
    }
    int v = h2;
    for (int i = 1; i <= q; i++) {
      v = (1LL * x2 * v) % m + y22, v %= m;
    }
    if (v == a2) {
      cout << q << endl;
      continue;
    }
    int c = 0;
    for (int i = 1; i <= m && !c; i++) {
      u = (1LL * x1 * u) % m + y11, u %= m;
      if (u == a1) c = i;
    }
    if (!c) {
      cout << -1 << endl;
      continue;
    }
    int o = 0;
    build(c);
    for (int i = 1; i <= m && !o; i++) {
      v = f(v);
      if (v == a2) o = i;
    }
    if (!o) {
      cout << -1 << endl;
      continue;
    }
    cout << 1LL * o * c + q << endl;
  }
}
