#include <bits/stdc++.h>
using namespace std;
long long m;
map<long long, int> goodTime;
long long prepare(bool output) {
  long long init, want;
  long long k, b;
  cin >> init >> want >> k >> b;
  vector<long long> xs;
  for (int i = 1; i <= 2 * m; i++) {
    init = (init * k + b) % m;
    if (init == want) {
      if (xs.size() < 2) xs.push_back(i);
    }
  }
  if (xs.size() == 0) return -1;
  long long delta = xs[1] - xs[0];
  long long v = xs[0];
  for (int i = 1; i <= m; i++) {
    if (output) {
      if (goodTime.count(v)) {
        return v;
      }
    } else
      goodTime[v] = true;
    v += delta;
  }
  return -1;
}
int MAIN() {
  cin >> m;
  prepare(0);
  cout << prepare(1) << endl;
  return 0;
}
int main() {
  int start = clock();
  ios ::sync_with_stdio(false);
  cout << fixed << setprecision(16);
  int ret = MAIN();
  return ret;
}
