#include <bits/stdc++.h>
using namespace std;
template <typename T1, typename T2>
ostream &operator<<(ostream &out, pair<T1, T2> a) {
  return (out << "(" << a.first << "; " << a.second << ")");
}
template <typename T1>
ostream &operator<<(ostream &cout, vector<T1> &a) {
  if ((int)a.size() == 0) return (cout << "()");
  cout << "(" << a[0];
  for (int i = 1; i < (int)a.size(); i++) cout << "; " << a[i];
  cout << ")";
  return cout;
}
const int nmax = 1000 * 1000;
const int inf = 1000 * 1001;
const int mod = 1000 * 1000 * 1000 + 7;
const long double pi = acos(-1.0);
const long long infl = 1000ll * 1000ll * 1000ll * 1000ll * 1000ll * 1000ll;
int n;
long long x1, y1_dhs, m, a1, a2, x2, y2, h1, h2;
inline int go1(long long a) { return (x1 * a + y1_dhs) % m; }
inline int go2(long long a) { return (x2 * a + y2) % m; }
long long gcd(long long a, long long b) {
  if (a < b) swap(a, b);
  while (b > 0) {
    a = a % b;
    swap(a, b);
  }
  return a;
}
int main() {
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1_dhs;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  int f1 = 0, c1 = 0, f2 = 0, c2 = 0;
  while (f1 < inf && h1 != a1) {
    f1++, h1 = go1(h1);
  }
  while (f2 < inf && h2 != a2) f2++, h2 = go2(h2);
  h1 = go1(h1);
  h2 = go2(h2);
  c1 = c2 = 1;
  while (c1 < inf && h1 != a1) c1++, h1 = go1(h1);
  while (c2 < inf && h2 != a2) c2++, h2 = go2(h2);
  cerr << f1 << " " << f2 << " " << c1 << " " << c2 << "\n";
  if (f1 == inf || f2 == inf) {
    cout << -1 << endl;
    return 0;
  }
  if (f1 == f2) {
    cout << f1 << endl;
    return 0;
  }
  if (c1 != inf && (f2 - f1) > 0 && (f2 - f1) % c1 == 0) {
    cout << f2 << endl;
    return 0;
  }
  if (c2 != inf && (f1 - f2) > 0 && (f1 - f2) % c2 == 0) {
    cout << f1 << endl;
    return 0;
  }
  if (c1 == inf || c2 == inf ||
      (max(f1, f2) - min(f1, f2)) % gcd(c1, c2) != 0) {
    cout << -1 << endl;
    return 0;
  }
  for (long long i = 0; i < inf * 3; ++i) {
    long long t = f1 + i * c1;
    if (t < f2) continue;
    if ((t - f2) % c2 == 0) {
      cout << t << endl;
      return 0;
    }
  }
  cout << -1 << endl;
}
