#include <bits/stdc++.h>
using namespace std;
const int maxn = 2000000 + 10;
bool vis[maxn];
long long a, a1, b, b1, c, d, xa, ya, xb, yb, ha, hb, m, t, p, q;
inline void cal() {
  ha = (xa * ha + ya) % m;
  hb = (xb * hb + yb) % m;
}
int main() {
  cin >> m >> a >> c >> xa >> ya >> b >> d >> xb >> yb;
  ha = a;
  hb = b;
  t = 0;
  while (ha != c && !vis[ha]) {
    vis[ha] = 1;
    cal();
    t++;
  }
  if (vis[ha]) {
    cout << -1 << endl;
    return 0;
  }
  if (hb == d) {
    cout << t << endl;
    return 0;
  }
  a1 = t;
  memset(vis, 0, sizeof(vis));
  cal();
  t++;
  p++;
  while (ha != c && !vis[ha]) {
    vis[ha] = 1;
    cal();
    t++;
    p++;
  }
  if (vis[ha]) {
    cout << -1 << endl;
    return 0;
  }
  if (hb == d) {
    cout << t << endl;
    return 0;
  }
  memset(vis, 0, sizeof(vis));
  ha = a;
  hb = b;
  t = 0;
  while (hb != d && !vis[hb]) {
    vis[hb] = 1;
    cal();
    t++;
  }
  if (vis[hb]) {
    cout << -1 << endl;
    return 0;
  }
  if (ha == c) {
    cout << t << endl;
    return 0;
  }
  b1 = t;
  memset(vis, 0, sizeof(vis));
  cal();
  t++;
  q++;
  while (hb != d && !vis[hb]) {
    vis[hb] = 1;
    cal();
    t++;
    q++;
  }
  if (vis[hb]) {
    cout << -1 << endl;
    return 0;
  }
  if (ha == c) {
    cout << t << endl;
    return 0;
  }
  long long lim = (long long)max(a1, b1) + p * q;
  for (long long i = a1; i <= lim; i += p)
    if (i >= b1 && (i - b1) % q == 0) {
      cout << i << endl;
      return 0;
    }
  cout << -1 << endl;
  return 0;
}
