#include <bits/stdc++.h>
using namespace std;
const int maxm = 1000050;
long long mod;
long long h[2], a[2], x[2], y[2];
long long fir[2], len[2];
bool used[maxm];
void calc() {
  for (int k = 0; k < 2; ++k) {
    fir[k] = -1;
    memset(used, 0, sizeof(used));
    long long cur = h[k], cnt = 0;
    while (1) {
      if (used[cur]) break;
      if (cur == a[k]) {
        fir[k] = cnt;
        break;
      }
      ++cnt;
      used[cur] = true;
      cur = (cur * x[k] + y[k]) % mod;
    }
    len[k] = -1;
    memset(used, 0, sizeof(used));
    cur = a[k], cnt = 0;
    while (1) {
      if (used[cur]) {
        if (cur == a[k]) len[k] = cnt;
        break;
      }
      ++cnt;
      used[cur] = true;
      cur = (cur * x[k] + y[k]) % mod;
    }
  }
}
int main() {
  scanf("%lld", &mod);
  for (int k = 0; k < 2; ++k) {
    scanf("%lld%lld", &h[k], &a[k]);
    scanf("%lld%lld", &x[k], &y[k]);
  }
  calc();
  if (fir[0] == -1 || fir[1] == -1)
    puts("-1");
  else if (len[0] == -1 && len[1] == -1) {
    if (fir[0] == fir[1])
      printf("%lld\n", fir[0]);
    else
      puts("-1");
  } else if (len[0] == -1 && len[1] != -1) {
    if (fir[0] >= fir[1] && (fir[0] - fir[1]) % len[1] == 0)
      printf("%lld\n", fir[0]);
    else
      puts("-1");
  } else if (len[0] != -1 && len[1] == -1) {
    if (fir[1] >= fir[0] && (fir[1] - fir[0]) % len[0] == 0)
      printf("%lld\n", fir[1]);
    else
      puts("-1");
  } else {
    long long ans = -1;
    for (long long i = 0; i < 1e6; ++i) {
      long long tmp = fir[0] + i * len[0] - fir[1];
      if (tmp >= 0 && tmp % len[1] == 0) {
        ans = tmp + fir[1];
        break;
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
