#include <bits/stdc++.h>
using namespace std;
bool same(long long x, long long y, long long mod) {
  return ((x % mod) == (y % mod));
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long m;
  cin >> m;
  long long h1, a1;
  cin >> h1 >> a1;
  long long x1, y1;
  cin >> x1 >> y1;
  long long h2, a2;
  cin >> h2 >> a2;
  long long x2, y2;
  cin >> x2 >> y2;
  long long it1 = 0;
  while (h1 != a1) {
    h1 = (h1 * x1 + y1) % m;
    ++it1;
    if (it1 > 2 * m + 3) {
      cout << -1;
      return 0;
    }
  }
  long long it2 = 0;
  while (h2 != a2) {
    h2 = (h2 * x2 + y2) % m;
    ++it2;
    if (it2 > 2 * m + 3) {
      cout << -1;
      return 0;
    }
  }
  if (it1 == it2) {
    cout << it1 << "\n";
    return 0;
  }
  long long per1 = 1;
  long long per2 = 1;
  h1 = (h1 * x1 + y1) % m;
  h2 = (h2 * x2 + y2) % m;
  while (h1 != a1) {
    h1 = (h1 * x1 + y1) % m;
    ++per1;
    if (per1 > 2 * m + 3) {
      per1 = 1000000000000000007;
      break;
    }
  }
  while (h2 != a2) {
    h2 = (h2 * x2 + y2) % m;
    ++per2;
    if (per2 > 2 * m + 3) {
      per2 = 1000000000000000007;
      break;
    }
  }
  int counter = 0;
  long long ans = 1000000000000000007;
  for (long long i = 0; i < 2 * m + 3; ++i) {
    if (it2 < it1 && it2 + i * per2 >= it1 &&
        (same(it2 + i * per2, it1, per1))) {
      ans = it2 + i * per2;
      break;
    }
    if (it1 < it2 && it1 + i * per1 >= it2 &&
        (same(it1 + i * per1, it2, per2))) {
      ans = it1 + i * per1;
      break;
    }
  }
  if (ans < 1000000000000000007) {
    cout << ans;
    return 0;
  }
  cout << -1 << "\n";
  return 0;
}
