#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
void solve() {
  long long i, j, k, l, r, m, n, a, b, c, d, x, y, z, t, p, q, s;
  cin >> m;
  cin >> a >> b;
  cin >> p >> q;
  cin >> c >> d;
  cin >> r >> s;
  long long ans = 0;
  for (i = 0; i <= m; i++) {
    if (a == b) break;
    a = (p * a + q);
    c = (r * c + s);
    a %= m;
    c %= m;
    ans++;
  }
  if (a != b) {
    cout << -1 << endl;
    return;
  }
  if (c == d) {
    cout << ans << endl;
    return;
  }
  n = 0;
  for (i = 1; i <= m; i++) {
    a = a * p + q;
    a %= m;
    if (a == b) {
      n = i;
      break;
    }
  }
  if (!n) {
    cout << -1 << endl;
    return;
  }
  k = 1;
  l = 0;
  for (i = 1; i <= n; i++) {
    l += k * s;
    l %= m;
    k *= r;
    k %= m;
  }
  for (i = 1; i <= m; i++) {
    c = c * k + l;
    c %= m;
    ans += n;
    if (c == d) {
      cout << ans << endl;
      return;
    }
  }
  cout << -1 << endl;
}
int32_t main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long t = 1;
  while (t--) solve();
  return 0;
}
