#include <bits/stdc++.h>
using namespace std;
const int MAXM = 1000010;
const int MAXL = 20;
int cnt1[MAXM];
int nx[MAXM][MAXL];
int main() {
  long long m, h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  long long cntr = 0;
  while (cnt1[h1] == 0) {
    if (h1 == a1 && h2 == a2) {
      cout << cntr << endl;
      return 0;
    }
    cnt1[h1] = cntr + 1;
    h1 = (x1 * h1 + y1) % m;
    h2 = (x2 * h2 + y2) % m;
    cntr++;
  }
  int len1 = cntr + 1 - cnt1[h1];
  int s1 = cnt1[h1];
  if (cnt1[a1] < s1) {
    cout << -1 << endl;
    return 0;
  }
  while (h1 != a1) {
    h1 = (x1 * h1 + y1) % m;
    h2 = (x2 * h2 + y2) % m;
    cntr++;
  }
  for (int i = 0; i < m; i++) nx[i][0] = (x2 * i + y2) % m;
  for (int i = 1; i < MAXL; i++)
    for (int j = 0; j < m; j++) nx[j][i] = nx[nx[j][i - 1]][i - 1];
  for (int i = 0; i < m; i++) {
    if (h1 == a1 && h2 == a2) {
      cout << cntr << endl;
      return 0;
    }
    cntr += len1;
    for (int j = 0; j < MAXL; j++)
      if ((len1 >> j) & 1) h2 = nx[h2][j];
  }
  cout << -1 << endl;
  return 0;
}
