#include <bits/stdc++.h>
using namespace std;
long long m, e, h, x, y;
long long cal() {
  for (int i = 0; i <= m * 2; i++) {
    h = (h * x + y) % m;
    if (h == e) return i + 1;
  }
  return -1;
}
void exgcd(long long a, long long b, long long& d, long long& x, long long& y) {
  if (!b)
    d = a, x = 1, y = 0;
  else {
    exgcd(b, a % b, d, y, x);
    y -= x * (a / b);
  }
}
int main() {
  cin >> m;
  cin >> h >> e >> x >> y;
  long long t1 = cal();
  long long t2 = cal();
  cin >> h >> e >> x >> y;
  long long t3 = cal();
  long long t4 = cal();
  if (t1 == t3) {
    cout << t1 << endl;
    return 0;
  }
  if (~t1 && ~t2 && ~t3 && t3 > t1 && (t3 - t1) % t2 == 0) {
    cout << t3 << endl;
    return 0;
  }
  if (~t3 && ~t4 && ~t1 && t1 > t3 && (t1 - t3) % t4 == 0) {
    cout << t1 << endl;
    return 0;
  }
  if (t1 == -1 || t2 == -1 || t3 == -1 || t4 == -1) {
    cout << -1 << endl;
    return 0;
  }
  long long x, y, d, a = t2, b = t4, c = t3 - t1;
  exgcd(a, b, d, x, y);
  if (c % d) {
    cout << -1 << endl;
    return 0;
  }
  x = (x * (c / d)) % b;
  x = (x % (b / d) + b / d) % (b / d);
  y = (a * x - c) / b;
  while (x < 0 || y < 0) x += d, y += d;
  cout << t1 + x * t2 << endl;
  return 0;
}
