#include <bits/stdc++.h>
using namespace std;
const int tam = 100010;
const long long MOD = 1000000007;
const int MOD1 = 998244353;
const double EPS = 1e-9;
const double PI = acos(-1);
int poa[10000001], pob[10000001], poad[10000001], pobd[10000001];
long long pot(long long b, long long e, long long m) {
  long long res = 1;
  while (e > 0) {
    if (e & 1) res = res * b % m;
    b = b * b % m;
    e /= 2;
  }
  return res;
}
long long x, y, d;
void extendedEuclid(long long a, long long b) {
  if (b == 0) {
    x = 1;
    y = 0;
    d = a;
    return;
  }
  extendedEuclid(b, a % b);
  long long x1 = y;
  y = x - (a / b) * y;
  x = x1;
}
int main() {
  int m, h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> m;
  cin >> h1 >> a1 >> x1 >> y1;
  cin >> h2 >> a2 >> x2 >> y2;
  poa[1] = x1;
  if (x1 <= 1) {
    for (long long i = 0; i < 10000001; i++) {
      poa[i] = x1;
      poad[i] = (i + 1) % m;
    }
  } else {
    for (long long i = 2; i < 10000001; i++) poa[i] = 1ll * poa[i - 1] * x1 % m;
    poad[0] = 1;
    for (long long i = 1; i < 10000001; i++)
      poad[i] = (poad[i - 1] + poa[i]) % m;
  }
  if (x2 <= 1) {
    for (long long i = 0; i < 10000001; i++) {
      pob[i] = x2;
      pobd[i] = (i + 1) % m;
    }
  } else {
    pob[1] = x2;
    for (long long i = 2; i < 10000001; i++) pob[i] = 1ll * pob[i - 1] * x2 % m;
    pobd[0] = 1;
    for (long long i = 1; i < 10000001; i++)
      pobd[i] = (pobd[i - 1] + pob[i]) % m;
  }
  long long a = -1, b = -1, pa = -1, push_back = -1;
  for (long long i = 1; i < 10000001; i++) {
    if ((1ll * poa[i] * h1 % m + 1ll * y1 * poad[i - 1]) % m == a1 && a != -1 &&
        pa == -1)
      pa = i - a;
    if ((1ll * pob[i] * h2 % m + 1ll * y2 * pobd[i - 1]) % m == a2 && b != -1 &&
        push_back == -1)
      push_back = i - b;
    if ((1ll * poa[i] * h1 % m + 1ll * y1 * poad[i - 1]) % m == a1 && a == -1)
      a = i;
    if ((1ll * pob[i] * h2 % m + 1ll * y2 * pobd[i - 1]) % m == a2 && b == -1)
      b = i;
    if ((1ll * poa[i] * h1 % m + 1ll * y1 * poad[i - 1]) % m == a1 &&
        (1ll * pob[i] * h2 % m + 1ll * y2 * pobd[i - 1]) % m == a2) {
      cout << i;
      return 0;
    }
  }
  long long A = pa, B = -push_back, C = b - a;
  extendedEuclid(A, B);
  long long a3 = B / d, b3 = A / d, X, Y;
  if (C % d != 0 || a == -1 || b == -1 || pa == -1 || push_back == -1) {
    cout << -1 << '\n';
  } else {
    x *= C / d;
    y *= C / d;
    long long re = MOD * MOD;
    long long gx, gy;
    for (long long i = 0; i < 10000001; i++) {
      X = x + a3 * i, Y = y - b3 * i;
      if (X >= 0 && Y >= 0 && a + pa * X > 0) {
        re = min(re, a + pa * X);
      }
      X = x + a3 * (-i), Y = y - b3 * (-i);
      if (X >= 0 && Y >= 0 && a + pa * X > 0) {
        re = min(re, a + pa * X);
      }
    }
    if (re == MOD * MOD)
      cout << "-1\n";
    else
      cout << re << '\n';
  }
}
