#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
const int maxint = 0x3f3f3f3f;
const int mod = 1e9 + 7;
long long n;
vector<long long> a[2][maxn];
void jisuan(long long t, long long p, long long x, long long y) {
  long long i = p, j = 0;
  a[t][i].push_back(j);
  while (1) {
    j++;
    i = (x * i + y) % n;
    if (a[t][i].size() == 2) return;
    a[t][i].push_back(j);
  }
}
int main() {
  long long i, p, h[2], x, y, k1, k2, b1, b2;
  cin >> n;
  for (i = 0; i <= 1; i++) {
    cin >> p >> h[i] >> x >> y;
    jisuan(i, p, x, y);
  }
  if (a[0][h[0]].size() * a[1][h[1]].size() == 0) {
    cout << "-1\n";
    return 0;
  }
  b1 = a[0][h[0]][0];
  b2 = a[1][h[1]][0];
  k1 = a[0][h[0]][1] - b1;
  k2 = a[1][h[1]][1] - b2;
  if (b1 == b2) {
    cout << b1 << "\n";
    return 0;
  }
  for (i = 1; i <= n * 4; i++) {
    if (b1 == b2) break;
    if (b1 < b2)
      b1 += k1;
    else
      b2 += k2;
  }
  if (b1 == b2)
    cout << b1 << "\n";
  else
    cout << "-1\n";
  return 0;
}
