#include <bits/stdc++.h>
using namespace std;
int M;
int vis[1000001];
bool F(long long x, long long y, long long h, long long a, long long &A,
       long long &C) {
  int count = 0;
  memset(vis, -1, sizeof(vis));
  vis[h] = 0;
  int First = -1, H1 = -1, H2 = -1;
  while (1) {
    h = (h * x + y) % M;
    count++;
    if (h == a) {
      if (!~First) First = count;
    }
    if (~vis[h]) {
      if (~First) {
        A = First;
        C = count - vis[h];
        if (First < vis[h]) C = 0;
        return true;
      } else
        return false;
    }
    vis[h] = count;
  }
  return false;
}
long long gcd(long long a, long long b) {
  while (b) {
    int t = a % b;
    a = b;
    b = t;
  }
  return a;
}
long long expgcd(long long a, long long b, long long &x, long long &y) {
  if (b) {
    long long gcd, nx, ny;
    gcd = expgcd(b, a % b, nx, ny);
    x = ny;
    y = nx - a / b * ny;
    return gcd;
  } else {
    x = 1;
    y = 0;
    return a;
  }
}
int main(void) {
  long long x1, y1, h1, a1, x2, y2, h2, a2, A1, C1, A2, C2;
  while (cin >> M >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2) {
    bool D1 = F(x1, y1, h1, a1, A1, C1), D2 = F(x2, y2, h2, a2, A2, C2);
    if (A1 > A2) {
      int t = A1;
      A1 = A2;
      A2 = t;
      t = C1;
      C1 = C2;
      C2 = t;
    }
    long long ANS;
    if (!D1 || !D2)
      ANS = -1;
    else {
      long long X, Y;
      if (A1 == A2)
        ANS = A1;
      else if (!C1 && !C2)
        ANS = -1;
      else if (!(C1 && C2)) {
        if (!C1) {
          if (A1 - A2 > 0 && (A1 - A2) % C2 == 0)
            ANS = A1;
          else
            ANS = -1;
        }
        if (!C2) {
          if (A2 - A1 > 0 && (A2 - A1) % C1 == 0)
            ANS = A2;
          else
            ANS = -1;
        }
      } else if ((A2 - A1) % gcd(C1, C2) == 0) {
        long long D = expgcd(C1, C2, X, Y);
        X *= (A2 - A1) / D;
        Y *= (A2 - A1) / D;
        int T1 = C1 / D, T2 = C2 / D;
        if (X >= T2) {
          int k = X / T2;
          X -= k * T2;
          Y += k * T1;
        }
        if (Y > 0) {
          int k = (Y - 1) / T1 + 1;
          X += k * T2;
          Y -= k * T1;
        }
        ANS = A1 + C1 * X;
      } else
        ANS = -1;
    }
    cout << ANS << endl;
  }
  return 0;
}
