#include <bits/stdc++.h>
using namespace std;
const int INF = (1 << 30) - 1;
const int mod = 1000000007;
const int maxn = 1000005;
int main() {
  long long m, h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  vector<int> g1;
  vector<int> g2;
  int ans = 0;
  while (ans <= 2 * m) {
    h1 = (x1 * h1 + y1) % m;
    h2 = (x2 * h2 + y2) % m;
    ans++;
    if (h1 == a1) g1.push_back(ans);
    if (h2 == a2) g2.push_back(ans);
  }
  if (g1.size() == 0 || g2.size() == 0) {
    puts("-1");
    return 0;
  }
  long long a = g1[0], b = g2[0];
  long long t1 = g1[1] - g1[0], t2 = g2[1] - g2[0];
  for (int i = 0; i < 9000000; i++) {
    if (a == b) {
      printf("%I64d\n", a);
      return 0;
    }
    if (a < b)
      a += t1;
    else
      b += t2;
  }
  printf("-1\n");
  return 0;
}
