#include <bits/stdc++.h>
using namespace std;
const int INF = (int)2e9;
const long long INFL = (long long)9e18;
const int MAXINT = ((~0) ^ (1 << 31));
const long long MAXLL = ((~0) ^ ((long long)1 << 63));
template <class T>
inline T pow2(T a) {
  return a * a;
}
template <class T>
inline bool mineq(T& a, T b) {
  return (a > b) ? (a = b, true) : false;
}
template <class T>
inline bool maxeq(T& a, T b) {
  return (a < b) ? (a = b, true) : false;
}
const int maxn = (int)2e6 + 10;
;
const int inf = 2e6;
bool vis[maxn];
long long h1, a1, x1, afdfsgd, h2, a2, x2, y2, MOD;
long long ans, c, q[maxn], p[maxn];
vector<int> v1, v2;
void Done() {
  cout << -1;
  exit(0);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> MOD >> h1 >> a1 >> x1 >> afdfsgd >> h2 >> a2 >> x2 >> y2;
  q[0] = y2;
  for (int i = 1; i < (int)(maxn); i++) {
    q[i] = (x2 * q[i - 1] + y2) % MOD;
  }
  p[0] = 1;
  for (int i = 1; i < (int)(maxn); i++) {
    p[i] = (p[i - 1] * x2) % MOD;
  }
  while (h1 != a1 && ans < inf) {
    h1 = (x1 * h1 + afdfsgd) % MOD;
    h2 = (x2 * h2 + y2) % MOD;
    ans++;
  }
  if (ans == inf) Done();
  if (h2 == a2) {
    cout << ans;
    return 0;
  }
  bool f = false;
  while ((!f || h1 != a1) && c < inf) {
    h1 = (x1 * h1 + afdfsgd) % MOD;
    c++;
    f = true;
  }
  if (c == inf) Done();
  int cnt = 0;
  while (h2 != a2 && cnt < inf) {
    h2 = (p[c] * h2 + q[c - 1]) % MOD;
    ans += c;
    cnt++;
  }
  if (cnt == inf) Done();
  cout << ans;
}
