#include <bits/stdc++.h>
using namespace std;
long long int findTick(long long int m, long long int h, long long int x,
                       long long int y, long long int a) {
  long long int tick = 0;
  while (tick < m) {
    tick++;
    h = (x * h + y) % m;
    if (h == a) return tick;
  }
  return -1;
}
int main() {
  long long int m, h1, x1, y1, a1, h2, x2, y2, a2;
  cin >> m >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;
  int s1 = findTick(m, h1, x1, y1, a1);
  if (s1 == -1) {
    printf("-1");
    return 0;
  }
  int c1 = findTick(m, a1, x1, y1, a1);
  long long int h3 = h2;
  long long int x3 = x2;
  long long int y3 = y2;
  for (int i = 0; i < s1; i++) h3 = (x2 * h3 + y2) % m;
  if (h3 == a2) {
    cout << s1;
    return 0;
  }
  if (c1 == -1) {
    cout << "-1";
    return 0;
  }
  for (int i = 1; i < c1; i++) {
    x3 = (x3 * x2) % m;
    y3 = (y3 * x2 + y2) % m;
  }
  long long int c3 = findTick(m, h3, x3, y3, a2);
  if (c3 != -1)
    cout << s1 + c1 * c3;
  else
    cout << "-1";
  return 0;
}
