#include <bits/stdc++.h>
using namespace std;
vector<int> ans1;
vector<int> ans2;
int main() {
  int n;
  long long h1, a1, x1, y1;
  long long h2, a2, x2, y2;
  int i, j;
  cin >> n;
  cin >> h1 >> a1 >> x1 >> y1;
  cin >> h2 >> a2 >> x2 >> y2;
  int s = 0;
  while (s <= 2 * n) {
    if (h1 == a1) ans1.push_back(s);
    if (h2 == a2) ans2.push_back(s);
    s++;
    h1 = (x1 * h1 + y1) % n;
    h2 = (x2 * h2 + y2) % n;
  }
  if (ans1.empty() || ans2.empty()) {
    cout << -1 << endl;
    return 0;
  }
  long long yy1 = ans1[0];
  long long yy2 = ans2[0];
  long long xx1 = ans1[1] - ans1[0];
  long long xx2 = ans2[1] - ans2[0];
  for (i = 0; i <= 5000000; i++) {
    if (yy1 == yy2) {
      cout << yy1 << endl;
      return 0;
    }
    if (yy1 > yy2) yy2 += xx2;
    if (yy1 < yy2) yy1 += xx1;
  }
  cout << -1 << endl;
  return 0;
}
