#include <bits/stdc++.h>
using namespace std;
int main() {
  int m;
  long long int h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  bool correct = false;
  long long int p1, t1, p2, t2;
  for (int i = 1; i <= m; i++) {
    h1 = (x1 * h1 + y1) % m;
    if (h1 == a1) {
      correct = true;
      t1 = i;
      break;
    }
  }
  if (!correct) {
    cout << "-1";
    return 0;
  }
  p1 = 0;
  for (int i = 1; i <= m; i++) {
    h1 = (x1 * h1 + y1) % m;
    if (h1 == a1) {
      p1 = i;
      break;
    }
  }
  correct = false;
  for (int i = 1; i <= m; i++) {
    h2 = (x2 * h2 + y2) % m;
    if (h2 == a2) {
      correct = true;
      t2 = i;
      break;
    }
  }
  if (!correct) {
    cout << "-1";
    return 0;
  }
  p2 = 0;
  for (int i = 1; i <= m; i++) {
    h2 = (x2 * h2 + y2) % m;
    if (h2 == a2) {
      p2 = i;
      break;
    }
  }
  for (int i = 0; i <= m; i++) {
    long long int cur = p1 * i + t1;
    if ((p2 != 0 && cur >= t2 && (cur - t2) % p2 == 0) ||
        (p2 == 0 && cur == t2)) {
      cout << cur << endl;
      return 0;
    }
  }
  cout << "-1";
  return 0;
}
