#include <bits/stdc++.h>
using namespace std;
int main() {
  long long m, h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> m;
  cin >> h1;
  cin >> a1;
  cin >> x1;
  cin >> y1;
  cin >> h2;
  cin >> a2;
  cin >> x2;
  cin >> y2;
  int qctr = 0;
  long long q1 = h1;
  long long q2 = h2;
  while (qctr < m && q1 != a1) {
    q1 = (q1 * x1 + y1) % m;
    q2 = (q2 * x2 + y2) % m;
    qctr += 1;
  }
  if (q1 == a1 && q2 == a2) {
    cout << qctr << endl;
    return 0;
  } else if (q1 != a1) {
    cout << -1 << endl;
    return 0;
  } else {
    int cctr = 1;
    q1 = (q1 * x1 + y1) % m;
    while (cctr < m && q1 != a1) {
      q1 = (q1 * x1 + y1) % m;
      cctr += 1;
    }
    if (q1 != a1) {
      cout << -1 << endl;
      return 0;
    } else {
      long long c = 1;
      long long d = 0;
      for (int i = 0; i < cctr; i++) {
        c = (c * x2) % m;
        d = (d * x2 + y2) % m;
      }
      int octr = 0;
      while (octr < m && q2 != a2) {
        q2 = (q2 * c + d) % m;
        octr += 1;
      }
      if (q2 != a2) {
        cout << -1 << endl;
        return 0;
      } else {
        long long temp = qctr + (long long)(octr)*cctr;
        cout << temp << endl;
        return 0;
      }
    }
  }
}
