#include <bits/stdc++.h>
using namespace std;
template <class T>
inline void chkmax(T& x, T y) {
  if (x < y) x = y;
}
template <class T>
inline void chkmin(T& x, T y) {
  if (y < x) x = y;
}
const int MX = 2000005;
long long m;
long long a[MX], b[MX];
long long ca[MX], cb[MX];
int main() {
  long long aa, bb, x1, y1, x2, y2;
  long long s1, t1, s2, t2, r1, r2;
  long long i, j;
  scanf("%I64d", &m);
  scanf("%I64d%I64d", &a[0], &aa);
  scanf("%I64d%I64d", &x1, &y1);
  scanf("%I64d%I64d", &b[0], &bb);
  scanf("%I64d%I64d", &x2, &y2);
  fill_n(ca, m, -1);
  ca[a[0]] = 0;
  for (i = 1;; i++) {
    a[i] = (x1 * a[i - 1] + y1) % m;
    if (ca[a[i]] != -1) break;
    ca[a[i]] = i;
  }
  s1 = ca[a[i]], t1 = i - s1;
  fill_n(cb, m, -1);
  cb[b[0]] = 0;
  for (i = 1;; i++) {
    b[i] = (x2 * b[i - 1] + y2) % m;
    if (cb[b[i]] != -1) break;
    cb[b[i]] = i;
  }
  s2 = cb[b[i]], t2 = i - s2;
  r1 = ca[aa], r2 = cb[bb];
  if (r1 == -1 || r2 == -1) {
    puts("-1");
    return 0;
  }
  if (r1 < s1) {
    i = r1;
    if (i >= s2) i = (i - s2) % t2 + s2;
    printf("%I64d\n", (b[i] == bb) ? r1 : -1);
    return 0;
  }
  if (r2 < s2) {
    i = r2;
    if (i >= s1) i = (i - s1) % t1 + s1;
    printf("%I64d\n", (a[i] == aa) ? r2 : -1);
    return 0;
  }
  if (r1 < r2) {
    swap(r1, r2);
    swap(t1, t2);
  }
  for (j = 0; j < t2; j++) {
    i = r1 + t1 * j;
    if (i % t2 == r2 % t2) break;
  }
  if (j == t2)
    puts("-1");
  else
    printf("%I64d\n", i);
  return 0;
}
