#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int mark1[maxn] = {0}, mark2[maxn] = {0};
int main() {
  long long m, h1, h2, a1, a2, x1, x2, y1, y2;
  cin >> m >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;
  long long r1 = -1, r2 = -1, p1 = -1, p2 = -1;
  for (int i = 1; i <= 2 * m; i++) {
    h1 = (h1 * x1 + y1) % m;
    if (h1 == a1) {
      if (p1 == -1)
        p1 = i;
      else if (r1 == -1)
        r1 = i - p1;
    }
    h2 = (h2 * x2 + y2) % m;
    if (h2 == a2) {
      if (p2 == -1)
        p2 = i;
      else if (r2 == -1)
        r2 = i - p2;
    }
  }
  if (p1 == -1 || p2 == -1) {
    cout << -1 << endl;
    return 0;
  }
  for (int i = 1; i <= 2 * m; i++) {
    if (p1 == p2) {
      cout << p1 << endl;
      return 0;
    }
    if (p1 < p2)
      p1 += r1;
    else
      p2 += r2;
  }
  cout << -1 << endl;
  return 0;
}
