#include <bits/stdc++.h>
using namespace std;
const int Maxm = 1e6 + 5;
long long repeat[2][3][Maxm], numRepeat[2][Maxm], period[2];
long long m, h[2], b[2], x[2], y[2];
void pre_process(int a) {
  int height = h[a], cnt = 0;
  for (int i = 0; i < Maxm; ++i)
    repeat[a][0][i] = repeat[a][1][i] = repeat[a][2][i] = -1;
  while (numRepeat[a][height] < 3) {
    ++numRepeat[a][height];
    int i = 0;
    while (i < 3 && repeat[a][i][height] != -1) ++i;
    repeat[a][i][height] = cnt;
    ++cnt;
    height = (x[a] * height + y[a]) % m;
  }
  if (repeat[a][0][b[a]] != -1 && repeat[a][1][b[a]] != -1)
    period[a] = repeat[a][1][b[a]] - repeat[a][0][b[a]];
}
int main() {
  cin >> m;
  for (int i = 0; i < 2; i++) cin >> h[i] >> b[i] >> x[i] >> y[i];
  pre_process(0);
  pre_process(1);
  cerr << repeat[0][0][b[0]] << ' ' << period[0] << '\t' << repeat[1][0][b[1]]
       << ' ' << period[1] << '\n';
  long long res = -1;
  if (repeat[0][0][b[0]] == repeat[1][0][b[1]]) res = repeat[0][0][b[0]];
  if (period[0] != 0) {
    for (int i = 0; i < 1e7; ++i)
      if ((repeat[1][0][b[1]] + i * period[1] - repeat[0][0][b[0]]) >= 0)
        if ((repeat[1][0][b[1]] + i * period[1] - repeat[0][0][b[0]]) %
                period[0] ==
            0) {
          res = repeat[1][0][b[1]] + i * period[1];
          break;
        }
  } else if (period[1] != 0) {
    for (int i = 0; i < 1e7; ++i)
      if ((repeat[0][0][b[0]] + i * period[0] - repeat[1][0][b[1]]) >= 0)
        if ((repeat[0][0][b[0]] + i * period[0] - repeat[1][0][b[1]]) %
                period[1] ==
            0) {
          res = repeat[0][0][b[0]] + i * period[0];
          break;
        }
  }
  cout << res << '\n';
  return 0;
}
