#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-9;
const long long INF = 1e15;
const long long MOD = 1e9 + 7;
const int N = 1000005;
const int M = 600000;
long long m;
long long h[3], a[3], x[3], y[3];
long long s[3], t[3];
int vis[1000005];
void read() {
  scanf("%I64d", &m);
  scanf("%I64d%I64d", h + 1, a + 1);
  scanf("%I64d%I64d", x + 1, y + 1);
  scanf("%I64d%I64d", h + 2, a + 2);
  scanf("%I64d%I64d", x + 2, y + 2);
}
bool get_st(int o) {
  memset(vis, 0, sizeof(vis));
  s[o] = 0;
  while (h[o] != a[o]) {
    vis[h[o]] = 1;
    h[o] = (h[o] * x[o] + y[o]) % m;
    s[o]++;
    if (vis[h[o]]) return false;
  }
  t[o] = 0;
  do {
    h[o] = (h[o] * x[o] + y[o]) % m;
    if (vis[h[o]] == 2) {
      t[o] = -1;
      break;
    }
    vis[h[o]] = 2;
    t[o]++;
  } while (h[o] != a[o]);
  return true;
}
long long ext_gcd(long long a, long long b, long long& x, long long& y) {
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  }
  long long d = ext_gcd(b, a % b, x, y), tmp = x;
  x = y;
  y = tmp - a / b * y;
  return d;
}
int main() {
  read();
  if (!get_st(1) || !get_st(2))
    printf("-1\n");
  else {
    if (t[1] == -1 && t[2] == -1) {
      if (s[1] == s[2])
        printf("%I64d\n", s[1]);
      else
        printf("-1\n");
    } else if (t[1] == -1) {
      if (s[1] >= s[2] && (s[1] - s[2]) % t[2] == 0)
        printf("%I64d\n", s[1]);
      else
        printf("-1\n");
    } else if (t[2] == -1) {
      if (s[2] >= s[1] && (s[2] - s[1]) % t[1] == 0)
        printf("%I64d\n", s[2]);
      else
        printf("-1\n");
    } else {
      if (s[2] < s[1]) {
        swap(s[1], s[2]);
        swap(t[1], t[2]);
      }
      long long x, y;
      int g = ext_gcd(t[1], t[2], x, y);
      long long d = s[2] - s[1];
      if (d % g != 0) {
        printf("-1\n");
      } else {
        x *= (d / g);
        x = (x % (t[2] / g) + t[2] / g) % (t[2] / g);
        long long ans = -1;
        while (true) {
          y = (s[1] - s[2] + x * t[1]) / t[2];
          if (y < 0) {
            x += t[2] / g;
            continue;
          }
          ans = s[1] + x * t[1];
          break;
        }
        printf("%I64d\n", ans);
      }
    }
  }
  return 0;
}
