#include <bits/stdc++.h>
inline int toInt(std::string s) {
  int v;
  std::istringstream sin(s);
  sin >> v;
  return v;
}
template <class T>
inline std::string toString(T x) {
  std::ostringstream sout;
  sout << x;
  return sout.str();
}
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  long long m;
  long long h1, a1, x1, y1;
  long long h2, a2, x2, y2;
  cin >> m;
  cin >> h1 >> a1 >> x1 >> y1;
  cin >> h2 >> a2 >> x2 >> y2;
  long long t1 = 0, s1 = 0;
  long long t2 = 0, s2 = 0;
  for (int i = 0; i < 2 * m + 1; i++) {
    h1 = (x1 * h1 + y1) % m;
    h2 = (x2 * h2 + y2) % m;
    if (h1 == a1) {
      if (s1 == 0) {
        s1 = i + 1;
      } else if (t1 == 0) {
        t1 = i + 1 - s1;
      }
    }
    if (h2 == a2) {
      if (s2 == 0) {
        s2 = i + 1;
      } else if (t2 == 0) {
        t2 = i + 1 - s2;
      }
    }
  }
  if (s1 == 0 || s2 == 0) {
    cout << -1 << endl;
    return 0;
  }
  for (int i = 0; i < 50000000; i++) {
    if (s1 == s2) {
      cout << s1 << endl;
      return 0;
    }
    if (s1 > s2) {
      if (t2 != 0)
        if ((s1 - s2) % t2 == 0) {
          cout << s1 << endl;
          return 0;
        }
      s2 += t2;
    } else if (s2 > s1) {
      if (t1 != 0)
        if ((s2 - s1) % t1 == 0) {
          cout << s2 << endl;
          return 0;
        }
      s1 += t1;
    }
  }
  cout << -1 << endl;
  return 0;
}
