#include <bits/stdc++.h>
using namespace std;
int vis[1000009];
int main() {
  vector<int> A, B;
  long long m, h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> m >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;
  memset(vis, 0, sizeof vis);
  long long H = h1;
  while (!vis[H]) {
    vis[H] = 1;
    A.push_back(H);
    H = (x1 * H + y1) % m;
  }
  int STA, STB;
  for (int i = 0; i < A.size(); i++) {
    if (A[i] == H) STA = i;
  }
  memset(vis, 0, sizeof vis);
  H = h2;
  while (!vis[H]) {
    vis[H] = 1;
    B.push_back(H);
    H = (x2 * H + y2) % m;
  }
  for (int i = 0; i < B.size(); i++) {
    if (B[i] == H) STB = i;
  }
  memset(vis, 0, sizeof vis);
  int K1 = -1, K2 = -1;
  for (int i = 0; i < A.size(); i++) {
    if (A[i] == a1) K1 = i;
  }
  for (int j = 0; j < B.size(); j++) {
    if (B[j] == a2) K2 = j;
  }
  if (K1 == -1 || K2 == -1) {
    cout << -1 << endl;
    return 0;
  }
  if (K1 == K2) {
    cout << K1 << endl;
    return 0;
  }
  if (K1 < STA && K2 < STB) {
    cout << -1 << endl;
    return 0;
  }
  if (K1 < STA && K2 >= STB) {
    if (K1 > K2 && (K1 - K2) % (B.size() - STB) == 0) {
      cout << K1 << endl;
    } else {
      cout << -1 << endl;
    }
    return 0;
  }
  if (K1 >= STB && K2 < STB) {
    if (K2 > K1 && (K2 - K1) % (A.size() - STA) == 0) {
      cout << K2 << endl;
    } else {
      cout << -1 << endl;
    }
    return 0;
  }
  K2 = K1 - STB;
  long long ans = K1;
  long long Mod = A.size() - STA;
  long long mod = B.size() - STB;
  if (K2 >= 0) {
    K2 = K2 % mod;
  }
  while (1) {
    if (vis[K2]) {
      cout << -1 << endl;
      return 0;
    }
    vis[K2] = 1;
    if (B[K2 + STB] == a2) {
      cout << ans << endl;
      return 0;
    }
    ans += Mod;
    if (K2 + Mod < 0) {
      K2 += Mod;
      continue;
    } else {
      K2 = (K2 + Mod) % mod;
    }
  }
}
