#include <bits/stdc++.h>
using namespace std;
long long m;
pair<long long, long long> func(long long x, long long h, long long y,
                                long long a) {
  vector<long long> res;
  for (int i = 0; i < (int)(2048000); i++) {
    if (h == a) res.push_back(i);
    if (res.size() == 2) return make_pair(res[0], res[1] - res[0]);
    h = (x * h + y) % m;
  }
  if ((int)res.size() == 1) return make_pair(res[0], 0);
  return make_pair(-1, -1);
}
long long solve() {
  cin >> m;
  long long h1, a1, x1, y1;
  long long h2, a2, x2, y2;
  cin >> h1 >> a1 >> x1 >> y1;
  cin >> h2 >> a2 >> x2 >> y2;
  long long p1, len1;
  tie(p1, len1) = func(x1, h1, y1, a1);
  long long p2, len2;
  tie(p2, len2) = func(x2, h2, y2, a2);
  if (p1 == -1 || p2 == -1) return -1;
  for (int i = 0; i < (int)(2048000); i++) {
    if (p1 == p2) return p1;
    if (p1 < p2)
      p1 += len1;
    else
      p2 += len2;
  }
  return -1;
}
int main() {
  cout << solve() << endl;
  return 0;
}
