#include <bits/stdc++.h>
using namespace std;
int M, h1, a1, X1, Y1, h2, a2, X2, Y2;
int length(int now, int dest, long long x, long long y) {
  int ret = 1;
  now = (x * now + y) % M;
  vector<int> visited(M);
  visited[now] = 1;
  while (now != dest) {
    now = (x * now + y) % M;
    ret++;
    if (visited[now]) return -1;
    visited[now] = 1;
  }
  return ret;
}
int main() {
  ios::sync_with_stdio(false);
  cin >> M >> h1 >> a1 >> X1 >> Y1 >> h2 >> a2 >> X2 >> Y2;
  int a = length(h1, a1, X1, Y1), b = length(a1, a1, X1, Y1);
  int c = length(h2, a2, X2, Y2), d = length(a2, a2, X2, Y2);
  if (a == -1 || c == -1)
    cout << -1;
  else if (a == c)
    cout << a;
  else {
    if (c < a) {
      swap(a, c);
      swap(b, d);
    }
    long long now = c - a;
    int t = b;
    if (b != -1) {
      for (t = 0; t < b; t++) {
        if (now % b == 0) break;
        if (d == -1) {
          t = b;
          break;
        }
        now += d;
      }
    }
    if (t == b)
      cout << -1;
    else
      cout << (long long)c + (long long)d * t;
  }
  return 0;
}
