#include <bits/stdc++.h>
using namespace std;
const long long Maxn = 1e6 + 7;
const long long Max = 1e3 + 7;
const long long Mod = 1e9 + 7;
const long long Inf = 1e6 + 7;
vector<long long> V[Maxn], G[Maxn];
bool mark[3][Maxn];
long long m, t[3], k[3], ans1, ans2, depth[3][Maxn];
void dfs(long long u, long long y, long long o) {
  mark[y][u] = true;
  depth[y][u] = o;
  o++;
  long long v = V[u][0];
  if (y == 2) v = G[u][0];
  if (!mark[y][v])
    dfs(v, y, o);
  else
    t[y] = v, k[y] = u;
}
int main() {
  long long m, h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> m >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;
  for (long long i = 0; i < m; i++) V[i].push_back((x1 * i + y1) % m);
  for (long long i = 0; i < m; i++) G[i].push_back((x2 * i + y2) % m);
  dfs(h1, 1, 0);
  m = 0;
  dfs(h2, 2, 0);
  if (!mark[1][a1] || !mark[2][a2]) {
    cout << -1 << endl;
    return 0;
  }
  if (depth[1][a1] == depth[2][a2]) {
    cout << depth[1][a1] << endl;
    return 0;
  }
  long long u1 = depth[1][t[1]], u2 = depth[2][t[2]];
  long long v1 = depth[1][a1], v2 = depth[2][a2];
  long long n1 = depth[1][k[1]], n2 = depth[2][k[2]];
  if (u1 > v1 && u2 > v2) {
    cout << -1 << endl;
    return 0;
  }
  if (u1 > v1) {
    u2 = n2 - u2 + 1;
    if ((v1 - v2) >= 0 && (v1 - v2) % u2 == 0) {
      cout << v1 << endl;
      return 0;
    } else {
      cout << -1 << endl;
      return 0;
    }
  } else if (u2 > v2) {
    u1 = n1 - u1 + 1;
    if (v2 >= v1 && (v2 - v1) % u1 == 0) {
      cout << v2 << endl;
      return 0;
    } else {
      cout << -1 << endl;
      return 0;
    }
  }
  u1 = n1 - u1 + 1;
  u2 = n2 - u2 + 1;
  for (long long i = 0; i <= 1e6; i++) {
    n1 = u1 * i + v1;
    if ((n1 - v2) % u2 == 0 && n1 - v2 >= 0) {
      cout << n1 << endl;
      return 0;
    }
  }
  cout << -1 << endl;
  return 0;
}
