#include <bits/stdc++.h>
using namespace std;
char v[1000006];
int main() {
  long long h1, a1, x1, y1, h2, a2, x2, y2;
  int m;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  int L1, L2;
  int t1 = -1, i, t2 = -1;
  for (i = 0; i < m; i++) v[i] = 0;
  v[h1] = 1;
  for (i = 1; i <= m; i++) {
    h1 = (((x1 * h1) % m) + y1) % m;
    if (v[h1]) {
      break;
    } else
      v[h1] = 1;
    if (h1 == a1) {
      t1 = i;
      break;
    }
  }
  if (t1 == -1) {
    puts("-1");
    return 0;
  }
  t2 = -1;
  for (i = 0; i < m; i++) v[i] = 0;
  v[h2] = 1;
  for (i = 1; i <= m; i++) {
    h2 = (((x2 * h2) % m) + y2) % m;
    if (v[h2]) {
      break;
    } else
      v[h2] = 1;
    if (h2 == a2) {
      t2 = i;
      break;
    }
  }
  if (t2 == -1) {
    puts("-1");
    return 0;
  }
  if (t1 == t2) {
    printf("%d\n", t1);
    return 0;
  }
  h1 = a1;
  for (i = 1; i <= m; i++) {
    h1 = (((x1 * h1) % m) + y1) % m;
    if (h1 == a1) {
      L1 = i;
      break;
    }
  }
  h2 = a2;
  for (i = 1; i <= m; i++) {
    h2 = (((x2 * h2) % m) + y2) % m;
    if (h2 == a2) {
      L2 = i;
      break;
    }
  }
  long long Ans = -1;
  for (i = 0; i <= m; i++) {
    long long x, y;
    x = t1 + (long long)L1 * i;
    if (x >= t2 && (L2 != 0 && (x - t2) % L2 == 0)) {
      Ans = x;
      break;
    }
  }
  cout << Ans << endl;
  return 0;
}
