#include <bits/stdc++.h>
using namespace std;
const long long maxN = 1e6 + 5;
const long long inf = 1e10;
const long long mod = 1e9 + 7;
long long m;
long long h1, a1, x, y;
long long h2, a2, u, v;
long long check1[maxN];
vector<long long> v1, v2;
long long check2[maxN];
long long ans[maxN];
int main() {
  ios_base::sync_with_stdio(0);
  cin >> m;
  cin >> h1 >> a1 >> x >> y;
  cin >> h2 >> a2 >> u >> v;
  long long cs1 = 1;
  long long res1 = 0;
  long long T1 = 0;
  while (1) {
    if (check1[h1] != 0) {
      res1 = check1[h1];
      T1 = cs1 - res1;
      break;
    }
    v1.push_back(h1);
    check1[h1] = cs1;
    cs1++;
    h1 = x * h1 + y;
    h1 %= m;
  }
  long long cs2 = 1;
  long long res2 = 0;
  long long T2 = 0;
  while (1) {
    if (check2[h2] != 0) {
      res2 = check2[h2];
      T2 = cs2 - res2;
      break;
    }
    v2.push_back(h2);
    check2[h2] = cs2;
    cs2++;
    h2 = u * h2 + v;
    h2 %= m;
  }
  if (check1[a1] == 0 || check2[a2] == 0) {
    cout << -1;
    return 0;
  }
  if (check1[a1] < res1 && check2[a2] < res2) {
    if (check1[a1] == check2[a2]) {
      cout << check1[a1] - 1;
      return 0;
    } else {
      cout << -1;
      return 0;
    }
  }
  if (check1[a1] < res1 && check2[a2] >= res2) {
    long long tam = check1[a1];
    if (tam >= check2[a2]) {
      if ((tam - check2[a2]) % T2 == 0) {
        cout << tam - 1;
        return 0;
      } else {
        cout << -1;
        return 0;
      }
    } else {
      cout << -1;
      return 0;
    }
  }
  if (check1[a1] >= res1 && check2[a2] < res2) {
    long long tam = check2[a2];
    if (tam >= check1[a1]) {
      if ((tam - check1[a1]) % T1 == 0) {
        cout << tam - 1;
        return 0;
      } else {
        cout << -1;
        return 0;
      }
    } else {
      cout << -1;
      return 0;
    }
  }
  for (long long i = 0; i <= maxN; i++) {
    long long tam = check1[a1] + i * T1;
    if (tam >= check2[a2]) {
      if ((tam - check2[a2]) % T2 == 0) {
        cout << tam - 1;
        return 0;
      }
    }
  }
  cout << -1;
  return 0;
}
