#include <bits/stdc++.h>
using namespace std;
int main() {
  long long c, e, f1, f2, i, j, k, flag, p, q, m;
  long long ans, x1, x2, y1, y2, a1, a2, h1, h2;
  long long r, s, t;
  scanf("%lld", &m);
  scanf("%lld %lld", &h1, &a1);
  scanf("%lld %lld", &x1, &y1);
  scanf("%lld %lld", &h2, &a2);
  scanf("%lld %lld", &x2, &y2);
  p = q = 0;
  for (i = 0; i < m; i++) {
    h1 = (x1 * h1 + y1) % m;
    if (h1 == a1) {
      p = i + 1;
      break;
    }
  }
  if (p == 0)
    ans = -1;
  else {
    h1 = a1;
    c = 0;
    for (i = 0; i < m; i++) {
      h1 = (x1 * h1 + y1) % m;
      if (h1 == a1) {
        c = i + 1;
        break;
      }
    }
    if (!c) flag = 1;
    for (i = 0; i < p; i++) h2 = (x2 * h2 + y2) % m;
    if (h2 == a2)
      ans = p;
    else {
      r = 1;
      s = 0;
      t = 0;
      e = h2;
      for (i = 0; i < c; i++) {
        r = (x2 * r) % m;
        s = (x2 * s + y2) % m;
      }
      for (i = 0; i < m; i++) {
        e = (r * e + s) % m;
        if (e == a2) {
          t = i + 1;
          break;
        }
      }
      if (!t)
        ans = -1;
      else
        ans = p + c * t;
    }
  }
  printf("%lld\n", ans);
  return 0;
}
