#include <bits/stdc++.h>
using namespace std;
long long q1[1000111], q2[1000111];
int main() {
  long long m;
  cin >> m;
  long long h1, a1, x1, y1;
  cin >> h1 >> a1 >> x1 >> y1;
  long long h2, a2, x2, y2;
  cin >> h2 >> a2 >> x2 >> y2;
  long long len1 = 0, len2 = 0, start1 = 0, start2 = 0;
  q1[h1] = 1;
  for (int i = 2; i <= 1e7; i++) {
    h1 = (x1 * h1 + y1) % m;
    if (q1[h1] == 0)
      q1[h1] = i;
    else {
      len1 = i - q1[h1];
      start1 = q1[h1];
      break;
    }
  }
  q2[h2] = 1;
  for (int i = 2; i <= 1e7; i++) {
    h2 = (x2 * h2 + y2) % m;
    if (q2[h2] == 0)
      q2[h2] = i;
    else {
      len2 = i - q2[h2];
      start2 = q2[h2];
      break;
    }
  }
  if (q1[a1] == 0 || q2[a2] == 0) {
    cout << -1 << endl;
    return 0;
  }
  if (q1[a1] < start1 && q2[a2] < start2) {
    cout << -1 << endl;
    return 0;
  }
  if (q1[a1] < start1) {
    long long d = (q1[a1] - q2[a2]) / len2;
    if (d >= 0 && q2[a2] + d * len2 == q1[a1]) {
      cout << q2[a2] + d * len2 - 1 << endl;
    } else
      cout << -1 << endl;
    return 0;
  }
  if (q2[a2] < start2) {
    long long d = (q2[a2] - q1[a1]) / len1;
    if (d >= 0 && q1[a1] + d * len1 == q2[a2]) {
      cout << q1[a1] + d * len1 - 1 << endl;
    } else
      cout << -1 << endl;
    return 0;
  }
  long long res = -1;
  long long d = (q1[a1] - q2[a2]);
  for (long long i = 0; i <= 1e7; i++) {
    long long j = (d + i * len1) / len2;
    if (j < 0) continue;
    if (q1[a1] + i * len1 == q2[a2] + j * len2) {
      if (q1[a1] + i * len1 < res || res == -1) res = q1[a1] + i * len1;
    }
  }
  if (res > 0) res--;
  cout << res << endl;
}
