#include <bits/stdc++.h>
using namespace std;
long long val[2];
pair<long long, long long> sum(pair<long long, long long> u,
                               pair<long long, long long> v) {
  return make_pair(u.first + v.first, u.second + v.second);
}
pair<long long, long long> prod(pair<long long, long long> u, long long k) {
  return make_pair(k * u.first, k * u.second);
}
long long f(pair<long long, long long> u) {
  return val[0] * u.first + val[1] * u.second;
}
pair<long long, long long> euc(pair<long long, long long> u,
                               pair<long long, long long> v) {
  long long ku = f(u), kv = f(v);
  if (kv == 0) return u;
  pair<long long, long long> res = euc(v, sum(u, prod(v, -ku / kv)));
  if (0 < f(res)) return res;
  return prod(res, -1);
}
long long solve(long long A, long long B, long long C) {
  val[0] = A;
  val[1] = B;
  pair<long long, long long> mat = euc(make_pair(1, 0), make_pair(0, 1));
  long long d = f(mat);
  if (C % d) return -1;
  long long xo = (C / d) * mat.first;
  long long yo = (C / d) * mat.second;
  while (xo < 0 || yo < 0) {
    xo -= (B / d);
    yo += (A / d);
  }
  while ((-B / d) < xo && (A / d) < yo) {
    xo += (B / d);
    yo -= (A / d);
  }
  return xo;
}
const int N = (1e6) + 10;
int m;
int h[2], a[2], x[2], y[2];
int abol[N], reg_abol[N];
int xaniar[N], reg_xaniar[N];
int main() {
  cin >> m;
  cin >> h[0] >> a[0] >> x[0] >> y[0];
  cin >> h[1] >> a[1] >> x[1] >> y[1];
  abol[0] = h[0];
  xaniar[0] = h[1];
  for (int i = 1; i <= m; i++)
    abol[i] = ((((long long)x[0] * abol[i - 1]) % m) + y[0]) % m;
  for (int i = 1; i <= m; i++)
    xaniar[i] = ((((long long)x[1] * xaniar[i - 1]) % m) + y[1]) % m;
  memset(reg_abol, -1, sizeof reg_abol);
  memset(reg_xaniar, -1, sizeof reg_xaniar);
  for (int i = 0; i < (int)m + 1; i++) {
    if (reg_abol[abol[i]] == -1) {
      reg_abol[abol[i]] = i;
      continue;
    }
    if (reg_abol[a[0]] == -1) {
      cout << -1;
      return 0;
    }
    if (reg_abol[a[0]] < reg_abol[abol[i]]) {
      if (xaniar[reg_abol[a[0]]] == a[1])
        cout << reg_abol[a[0]];
      else
        cout << -1;
      return 0;
    }
    for (int j = 0; j < (int)m + 1; j++) {
      if (reg_xaniar[xaniar[j]] == -1) {
        reg_xaniar[xaniar[j]] = j;
        continue;
      }
      if (reg_xaniar[a[1]] == -1) {
        cout << -1;
        return 0;
      }
      if (reg_xaniar[a[1]] < reg_xaniar[xaniar[j]]) {
        if (abol[reg_xaniar[a[1]]] == a[0])
          cout << reg_xaniar[a[1]];
        else
          cout << -1;
        return 0;
      }
      long long p0 = i - reg_abol[abol[i]];
      long long p1 = j - reg_xaniar[xaniar[j]];
      long long k = reg_abol[a[0]] - reg_xaniar[a[1]];
      long long sol = solve(p0, -p1, -k);
      if (sol < 0)
        cout << -1;
      else
        cout << sol * p0 + reg_abol[a[0]];
      return 0;
    }
  }
}
