#include <bits/stdc++.h>
using namespace std;
int m;
long long h1, a1, h2, a2, x1, y11, x2, y2;
long long next(long long a, long long x, long long y, long long mod) {
  return (a * x + y) % mod;
}
int main() {
  while (cin >> m) {
    cin >> h1 >> a1 >> x1 >> y11;
    cin >> h2 >> a2 >> x2 >> y2;
    long long k1 = 0;
    while (h1 != a1 && k1 < m + 10) {
      h1 = next(h1, x1, y11, m);
      h2 = next(h2, x2, y2, m);
      k1++;
    }
    if (h1 != a1) {
      puts("-1");
      continue;
    }
    if (h1 == a1 && h2 == a2) {
      cout << k1 << endl;
      continue;
    }
    int cycle = 1;
    h1 = next(h1, x1, y11, m);
    int x = x2, y = y2;
    while (h1 != a1 && cycle < m + 10) {
      h1 = next(h1, x1, y11, m);
      x = (x * x2) % m;
      y = (y * x2 + y2) % m;
      cycle++;
    }
    if (h1 != a1) {
      puts("-1");
      continue;
    }
    long long k2 = 0;
    while (h2 != a2 && k2 < m + 10) {
      h2 = next(h2, x, y, m);
      k2++;
    }
    if (h2 != a2) {
      puts("-1");
      continue;
    } else {
      cout << k2 * cycle + k1 << endl;
    }
  }
  return 0;
}
