#include <bits/stdc++.h>
using namespace std;
long long m, h1, h2, a1, a2, xx1, xx2, yy1, yy2;
long long ok1, ok2, ck1, ck2, dem1, dem2, du1, du2, dau1, dau2;
int dd[1000005];
vector<long long> v1, v2;
void tim(long long h, long long a, long long xx, long long yy,
         vector<long long> &v, long long &ok) {
  memset(dd, 0, sizeof(dd));
  ok = 0;
  while (!dd[h]) {
    dd[h] = 1;
    v.push_back(h);
    if (h == a) ok = 1;
    h = (h * xx + yy) % m;
  }
  v.push_back(h);
}
void kiem(vector<long long> &v, long long &ck, long long &dem, long long &du,
          long long &dau, long long a) {
  long long vt;
  dem = -1;
  dau = -1;
  for (long long i = 0; i < v.size(); i++)
    if (v[i] == v.back()) {
      vt = i;
      break;
    }
  ck = v.size() - vt - 1;
  du = vt;
  for (long long i = 0; i < v.size(); i++) {
    if (v[i] == a && i < vt) dau = i;
    if (v[i] == a && i >= vt) {
      dem = i - vt;
      break;
    }
  }
}
long long tinh() {
  long long c = dem2 + du2 - dem1 - du1;
  while (c < 0) c += ck1;
  long long k = ck1 - c % ck1;
  long long res;
  for (int i = 0; i <= 1000000; i++)
    if ((ck2 * i + du2 + dem2 - du1 - dem1) % ck1 == 0) {
      cout << ck2 * i + du2 + dem2;
      exit(0);
    }
}
void doi() {
  swap(ck1, ck2);
  swap(dem1, dem2);
  swap(du1, du2);
  swap(dau1, dau2);
}
int main() {
  cin >> m;
  cin >> h1 >> a1 >> xx1 >> yy1;
  cin >> h2 >> a2 >> xx2 >> yy2;
  v1.clear();
  v2.clear();
  tim(h1, a1, xx1, yy1, v1, ok1);
  tim(h2, a2, xx2, yy2, v2, ok2);
  if (!ok1 || !ok2) {
    cout << -1;
    exit(0);
  }
  for (long long i = 1; i < min(v1.size(), v2.size()) - 1; i++)
    if (v1[i] == a1 && v2[i] == a2) {
      cout << i;
      exit(0);
    }
  kiem(v1, ck1, dem1, du1, dau1, a1);
  kiem(v2, ck2, dem2, du2, dau2, a2);
  if (dem1 < 0 && dem2 < 0) {
    cout << -1;
    exit(0);
  }
  if (dem1 < 0 && dau1 > 0 || dem2 < 0 && dau2 > 0) {
    if (dem1 < 0) doi();
    long long k = dau2 - du1 - dem1;
    if (k % ck1 == 0 && k > 0)
      cout << dau2;
    else
      cout << -1;
    exit(0);
  }
  if (ck1 < ck2) doi();
  if (ck1 % ck2 == 0 && ck2 != 1) {
    if ((du1 + dem1 - du2 - dem2) % ck2 == 0)
      cout << du1 + dem1 << endl;
    else
      cout << -1;
    exit(0);
  }
  cout << tinh();
  return 0;
}
