#include <bits/stdc++.h>
using namespace std;
long long egcd(long long a, long long b, long long& x, long long& y) {
  if (!b) {
    x = 1;
    y = 0;
    return a;
  }
  long long d = egcd(b, a % b, y, x);
  y -= x * (a / b);
  return d;
}
bool canon_egcd(long long a, long long b, long long c, long long& x,
                long long& y) {
  long long d = egcd(a, b, x, y), z = abs(a / d);
  if (c % d) return false;
  y = (y * (c / d) % z + z) % z, x = (c - b * y) / a;
  return true;
}
long long m;
inline long long f(const long long& h, const long long& x, const long long& y) {
  return (x * h + y) % m;
}
bool v[1000001];
int main() {
  long long h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> m >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;
  long long PLS1 = h1, PLS2 = h2;
  for (int i = 0; i <= 1000; i++) {
    if (PLS1 == a1 && PLS2 == a2) {
      cout << i << "\n";
      return 0;
    }
    PLS1 = f(PLS1, x1, y1);
    PLS2 = f(PLS2, x2, y2);
  }
  long long d1 = 0, c1 = 1;
  v[h1] = true;
  while (h1 != a1) {
    h1 = f(h1, x1, y1);
    if (v[h1]) {
      cout << "-1\n";
      return 0;
    }
    v[h1] = true;
    d1++;
  }
  memset(v, 0, sizeof v);
  h1 = f(h1, x1, y1);
  v[h1] = true;
  while (h1 != a1) {
    h1 = f(h1, x1, y1);
    if (v[h1]) {
      cout << "-1\n";
      return 0;
    }
    v[h1] = true;
    c1++;
  }
  long long d2 = 0, c2 = 1;
  memset(v, 0, sizeof v);
  v[h2] = true;
  while (h2 != a2) {
    h2 = f(h2, x2, y2);
    if (v[h2]) {
      cout << "-1\n";
      return 0;
    }
    v[h2] = true;
    d2++;
  }
  memset(v, 0, sizeof v);
  h2 = f(h2, x2, y2);
  v[h2] = true;
  while (h2 != a2) {
    h2 = f(h2, x2, y2);
    if (v[h2]) {
      cout << "-1\n";
      return 0;
    }
    v[h2] = true;
    c2++;
  }
  long long a = 0, x, y;
  if (d1 == d2)
    a = d1;
  else if (d1 > d2)
    a = canon_egcd(c1, c2, d1 - d2, x, y) ? y * c2 + d2 : -1;
  else
    a = canon_egcd(c2, c1, d2 - d1, x, y) ? y * c1 + d1 : -1;
  cout << a << "\n";
  return 0;
}
