#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
  if (a == b) {
    return a;
  }
  if (b == 1) {
    return a;
  }
  return gcd(b, a % b);
}
int main() {
  long long m, h1, a1, xx1, yy1, h2, a2, xx2, yy2;
  cin >> m >> h1 >> a1 >> xx1 >> yy1 >> h2 >> a2 >> xx2 >> yy2;
  bool go = true;
  long long T = 0;
  while (T < m + 1) {
    h1 = (h1 * xx1 + yy1) % m;
    h2 = (h2 * xx2 + yy2) % m;
    ++T;
    if (h1 == a1 && h2 == a2) {
      cout << T << endl;
      return 0;
    }
  }
  while (h1 != a1) {
    h1 = (h1 * xx1 + yy1) % m;
    h2 = (h2 * xx2 + yy2) % m;
    ++T;
    if (h1 == a1 && h2 == a2) {
      cout << T << endl;
      return 0;
    }
    if (T > 2 * m + 3) {
      cout << "-1" << endl;
      return 0;
    }
  }
  long long hh = h1;
  long long t1 = 0;
  go = true;
  while (go) {
    hh = (hh * xx1 + yy1) % m;
    ++t1;
    if (hh == h1) go = false;
  }
  hh = h2;
  long long t2 = 0;
  go = true;
  while (go) {
    hh = (hh * xx2 + yy2) % m;
    ++t2;
    if (hh == h2) go = false;
  }
  long long d2 = 0;
  go = true;
  hh = h2;
  while (go) {
    hh = (hh * xx2 + yy2) % m;
    ++d2;
    if (hh == a2) go = false;
    if (d2 > m + 3) {
      cout << "-1" << endl;
      return 0;
    }
  }
  long long k = (d2 + t1 - 1) / t1;
  while ((k * t1 - d2) % t2 != 0) {
    ++k;
    if (k > m + 2) {
      cout << "-1" << endl;
      return 0;
    }
  }
  cout << (k * t1 + T) << endl;
  return 0;
}
