#include <bits/stdc++.h>
using namespace std;
long long m, x1, ___y1, x2, ___y2;
long long h1, a1, h2, a2;
long long p1, p2;
int num1[1000000], num2[1000000];
bool in_period1[1000000], in_period2[1000000];
void walk1(int cur) {
  int nxt = (int)((cur * x1 + ___y1) % m);
  if (!in_period1[nxt]) {
    if (num1[nxt] == -1) {
      num1[nxt] = num1[cur] + 1;
    } else {
      if (!p1) {
        p1 = num1[cur] + 1 - num1[nxt];
      }
      in_period1[nxt] = true;
    }
    walk1(nxt);
  }
}
void walk2(int cur) {
  int nxt = (int)((cur * x2 + ___y2) % m);
  if (!in_period2[nxt]) {
    if (num2[nxt] == -1) {
      num2[nxt] = num2[cur] + 1;
    } else {
      if (!p2) {
        p2 = num2[cur] + 1 - num2[nxt];
      }
      in_period2[nxt] = true;
    }
    walk2(nxt);
  }
}
int main() {
  cin >> m >> h1 >> a1 >> x1 >> ___y1 >> h2 >> a2 >> x2 >> ___y2;
  for (int i = 0; i < m; i++) {
    num1[i] = num2[i] = -1;
  }
  num1[h1] = 0;
  walk1(h1);
  num2[h2] = 0;
  walk2(h2);
  if (num1[a1] == -1 || num2[a2] == -1) {
    cout << -1 << endl;
    return 0;
  }
  if (!in_period1[a1] && !in_period2[a2]) {
    if (num1[a1] == num2[a2]) {
      cout << num1[a1] << endl;
    } else {
      cout << -1 << endl;
    }
    return 0;
  }
  if (!in_period1[a1] && in_period2[a2]) {
    long long n = (num1[a1] - num2[a2]) / p2;
    if (n < 0 || (num1[a1] - num2[a2]) % p2 != 0) {
      cout << -1 << endl;
    } else {
      cout << num1[a1] << endl;
    }
    return 0;
  }
  if (in_period1[a1] && !in_period2[a2]) {
    long long n = (num2[a2] - num1[a1]) / p1;
    if (n < 0 || (num2[a2] - num1[a1]) % p1 != 0) {
      cout << -1 << endl;
    } else {
      cout << num2[a2] << endl;
    }
    return 0;
  }
  for (long long n1 = 0; n1 <= 1000000; n1++) {
    long long num = num1[a1] + p1 * n1;
    if (num >= num2[a2] && (num - num2[a2]) % p2 == 0) {
      cout << num << endl;
      return 0;
    }
  }
  cout << -1 << endl;
}
