#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 1e3;
const int INF = 1e9 + 9;
int m;
long long h[3], a[3], x[3], y[3], p[3];
int cnt[3], ccl[3];
int used[3][maxn];
vector<int> v[3];
void no() {
  printf("-1\n");
  exit(0);
}
int main() {
  scanf("%d", &m);
  for (int i = int(1); i <= int(2); ++i)
    scanf("%d %d %d %d", &h[i], &a[i], &x[i], &y[i]);
  for (int i = int(1); i <= int(2); ++i) {
    while (!used[i][h[i]]) {
      used[i][h[i]] = ++cnt[i];
      v[i].push_back(h[i]);
      h[i] = (x[i] * h[i] + y[i]) % m;
    }
    ccl[i] = used[i][h[i]] - 1;
    for (auto x : v[i]) --used[i][x];
  }
  int c1 = cnt[1] - ccl[1], c2 = cnt[2] - ccl[2];
  p[1] = used[1][a[1]];
  p[2] = used[2][a[2]];
  if (!p[1] || !p[2]) no();
  for (int i = int(0); i <= int(max(ccl[1], ccl[2])); ++i) {
    int p1 = (i < ccl[1] ? i : ccl[1] + (i - ccl[1]) % c1);
    int p2 = (i < ccl[2] ? i : ccl[2] + (i - ccl[2]) % c2);
    if (v[1][p1] == a[1] && v[2][p2] == a[2]) {
      printf("%d\n", i);
      return 0;
    }
  }
  if (p[1] < ccl[1] || p[2] < ccl[2]) no();
  long long mul = 1, shift = 0;
  for (int i = int(1); i <= int(c1); ++i) {
    mul = (mul * x[2]) % m;
    shift = (shift * x[2] + y[2]) % m;
  }
  long long cur = 0;
  if (p[1] >= ccl[2])
    cur = v[2][ccl[2] + ((p[1] - ccl[2]) % c2)];
  else
    cur = v[2][p[1]];
  for (int i = int(0); i <= int(m - 1); ++i) {
    if (cur == a[2]) {
      printf("%I64d\n", p[1] + 1LL * i * c1);
      return 0;
    }
    cur = ((cur * mul) + shift) % m;
  }
  no();
  return 0;
}
