#include <bits/stdc++.h>
using namespace std;
#pragma GCC target("avx2")
#pragma GCC optimization("O3")
#pragma GCC optimization("unroll-loops")
using matrix = vector<vector<int64_t>>;
int64_t MOD;
matrix mult(matrix x, matrix y) {
  int64_t N = x.size(), M = x[0].size(), P = y[0].size();
  matrix res = vector<vector<int64_t>>(N, vector<int64_t>(P, 0));
  for (int64_t i = 0; i < N; i++)
    for (int64_t j = 0; j < P; j++)
      for (int64_t k = 0; k < M; k++)
        res[i][j] = (res[i][j] + x[i][k] * y[k][j]) % MOD;
  return res;
}
matrix power(matrix x, int64_t y) {
  matrix res = vector<vector<int64_t>>(x.size(), vector<int64_t>(x.size(), 0));
  for (int64_t i = 0; i < x.size(); i++) res[i][i] = 1;
  while (y > 0) {
    if (y & 1) res = mult(res, x);
    x = mult(x, x);
    y >>= 1;
  }
  return res;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int64_t m;
  cin >> m;
  MOD = m;
  int64_t h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;
  int64_t until_h1_hits_a1 = -1;
  for (int64_t tmr = 0; tmr < m + 3; tmr++) {
    if (h1 == a1) {
      until_h1_hits_a1 = tmr;
      break;
    }
    h1 = (h1 * x1 + y1) % m;
    h2 = (h2 * x2 + y2) % m;
  }
  if (until_h1_hits_a1 < 0) {
    cout << -1;
    return 0;
  }
  if (h2 == a2) {
    cout << until_h1_hits_a1;
    return 0;
  }
  int64_t until_repeat = -1;
  int64_t before = h2;
  for (int64_t tmr = 1; tmr < m + 3; tmr++) {
    h1 = (h1 * x1 + y1) % m;
    h2 = (h2 * x2 + y2) % m;
    if (h1 == a1) {
      until_repeat = tmr;
      break;
    }
  }
  matrix base_mat = {{x2, 0}, {y2, 1}};
  matrix mid_mat = power(base_mat, until_repeat);
  int64_t leap_x = mid_mat[0][0], leap_y = mid_mat[1][0];
  for (int64_t cycles = 1; cycles < m + 5; cycles++) {
    if (h2 == a2) {
      cout << until_h1_hits_a1 + until_repeat * cycles;
      return 0;
    }
    h2 = (h2 * leap_x + leap_y) % m;
  }
  cout << -1;
  return 0;
}
