#include <bits/stdc++.h>
using namespace std;
long long h1, h2, a1, a2, x1, x2, y, y2, c, d, m, k, ans, w;
int main() {
  cin >> m >> h1 >> a1 >> x1 >> y >> h2 >> a2 >> x2 >> y2;
  while (h1 != a1) {
    k++;
    h1 = (h1 * x1 + y) % m;
    h2 = (h2 * x2 + y2) % m;
    if (k > m) {
      cout << -1 << endl;
      return 0;
    }
  }
  if (h2 == a2) {
    cout << k << endl;
    return 0;
  }
  ans = 1;
  h1 = (h1 * x1 + y) % m;
  c = 1;
  d = 0;
  c = (c * x2) % m;
  d = (x2 * d + y2) % m;
  while (h1 != a1) {
    ans++;
    h1 = (h1 * x1 + y) % m;
    c = (c * x2) % m;
    d = (x2 * d + y2) % m;
    if (ans > m) {
      cout << -1 << endl;
      return 0;
    }
  }
  w = 0;
  while (h2 != a2) {
    w++;
    h2 = (h2 * c + d) % m;
    if (w > m) {
      cout << -1 << endl;
      return 0;
    }
  }
  cout << k + ans * w << endl;
  return 0;
}
