#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
  if (a < 0) a = -a;
  if (b < 0) b = -b;
  if (a < b) {
    int tmp = a;
    a = b;
    b = a;
  }
  if (b == 0) return a;
  return gcd(b, a % b);
}
int lcm(int a, int b) { return a / gcd(a, b) * b; }
int main() {
  long long int m, h1, a1, h2, a2, x1, y1, x2, y2;
  long long int pd1 = 0, pd2 = 0, rem1 = 0, rem2 = 0;
  cin >> m >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;
  while (h1 != a1 && rem1 <= m) {
    h1 = x1 * h1 + y1;
    h1 %= m;
    rem1++;
  }
  while (h2 != a2 && rem2 <= m) {
    h2 = x2 * h2 + y2;
    h2 %= m;
    rem2++;
  }
  do {
    h1 = x1 * h1 + y1;
    h1 %= m;
    pd1++;
  } while (h1 != a1 && pd1 <= m);
  do {
    h2 = x2 * h2 + y2;
    h2 %= m;
    pd2++;
  } while (h2 != a2 && pd2 <= m);
  int ct2 = 0;
  while (rem1 != rem2 && rem1 < m && rem2 < m && ct2 < m) {
    if (rem1 < rem2 && pd1 <= m && rem1 + pd1 < m)
      rem1 += pd1;
    else if (rem1 > rem2 && pd2 <= m && rem2 + pd2 < m)
      rem2 += pd2;
    ct2++;
  }
  if (rem1 > m || rem2 > m || (pd1 > m || pd2 > m) && rem1 != rem2) {
    cout << "-1";
    return 0;
  }
  int ct = 0;
  while (ct < m * 2 && rem1 != rem2) {
    ct++;
    if (rem1 < rem2)
      rem1 += pd1;
    else if (rem1 > rem2)
      rem2 += pd2;
  }
  if (ct >= m * 2) {
    cout << "-1";
    return 0;
  }
  cout << rem1;
  return 0;
}
