#include <bits/stdc++.h>
using namespace std;
int A[1000005][2];
int B[1000005][2];
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
int main(void) {
  long long k, m;
  long long h1, a1, x1, y1;
  long long h2, a2, x2, y2;
  cin >> m;
  cin >> h1 >> a1 >> x1 >> y1;
  cin >> h2 >> a2 >> x2 >> y2;
  A[h1][0] = k = 1;
  while (A[a1][0] == 0) {
    h1 = (x1 * h1 + y1) % m;
    if (A[h1][0] == 0)
      A[h1][0] = ++k;
    else
      break;
  }
  A[h2][1] = k = 1;
  while (A[a2][1] == 0) {
    h2 = (x2 * h2 + y2) % m;
    if (A[h2][1] == 0)
      A[h2][1] = ++k;
    else
      break;
  }
  if (A[a1][0] == 0 || A[a2][1] == 0)
    cout << "-1" << endl;
  else {
    k = 0;
    h1 = a1;
    while (B[a1][0] == 0) {
      h1 = (x1 * h1 + y1) % m;
      if (B[h1][0] == 0)
        B[h1][0] = ++k;
      else
        break;
    }
    k = 0;
    h2 = a2;
    while (B[a2][1] == 0) {
      h2 = (x2 * h2 + y2) % m;
      if (B[h2][1] == 0)
        B[h2][1] = ++k;
      else
        break;
    }
    x1 = A[a1][0] - 1;
    x2 = A[a2][1] - 1;
    if (B[a1][0] == 0 || B[a2][1] == 0) {
      if (x1 == x2)
        cout << x1 << endl;
      else if (x1 + B[a1][0] == x2 + B[a2][1])
        cout << ((x1 + B[a1][0]) > (x2 + B[a2][1]) ? x1 + B[a1][0]
                                                   : x2 + B[a2][1])
             << endl;
      else
        cout << "-1" << endl;
    } else {
      if (B[a1][0] > B[a2][1])
        k = gcd(B[a1][0], B[a2][1]);
      else
        k = gcd(B[a2][1], B[a1][0]);
      if (x1 % k != x2 % k)
        cout << "-1" << endl;
      else {
        while (x1 != x2) {
          if (x1 < x2) {
            if ((x2 - x1) % B[a1][0] == 0)
              x1 += (x2 - x1) / B[a1][0] * B[a1][0];
            else
              x1 += (x2 - x1) / B[a1][0] * B[a1][0] + B[a1][0];
          } else {
            if ((x1 - x2) % B[a2][1] == 0)
              x2 += (x1 - x2) / B[a2][1] * B[a2][1];
            else
              x2 += (x1 - x2) / B[a2][1] * B[a2][1] + B[a2][1];
          }
        }
        cout << x1 << endl;
      }
    }
  }
  return 0;
}
