#include <bits/stdc++.h>
using namespace std;
int M;
long long H_1, A_1, H_2, A_2;
long long X_1, Y_1, X_2, Y_2;
int main() {
  cin.sync_with_stdio(false);
  cin >> M;
  cin >> H_1 >> A_1;
  cin >> X_1 >> Y_1;
  cin >> H_2 >> A_2;
  cin >> X_2 >> Y_2;
  int i, q = -1;
  for (i = 0; i < M; i++) {
    H_1 = (H_1 * X_1 + Y_1) % M;
    if (H_1 == A_1) {
      q = i + 1;
      break;
    }
  }
  if (q == -1) {
    cout << "-1" << endl;
    return 0;
  }
  for (i = 0; i < q; i++) {
    H_2 = (H_2 * X_2 + Y_2) % M;
  }
  if (H_2 == A_2) {
    cout << q << endl;
    return 0;
  }
  int c = -1;
  for (i = 0; i < M; i++) {
    H_1 = (H_1 * X_1 + Y_1) % M;
    if (H_1 == A_1) {
      c = i + 1;
      break;
    }
  }
  if (c == -1) {
    cout << "-1" << endl;
    return 0;
  }
  int a = 1, b = 0;
  for (i = 0; i < c; i++) {
    a = (a * X_2) % M;
    b = (b * X_2 + Y_2) % M;
  }
  int t = -1;
  for (i = 1; i <= M; i++) {
    H_2 = (H_2 * a + b) % M;
    if (H_2 == A_2) {
      t = i;
      break;
    }
  }
  if (t == -1) {
    cout << "-1" << endl;
    return 0;
  }
  cout << (long long)q + (long long)t * c << endl;
  return 0;
}
