#include <bits/stdc++.h>
using namespace std;
int main() {
  long long i, j, m, h1, h2, a1, a2, x1, x2, y1, y2, t1, t2, flag;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  long long p1, p2, u1, u2, fin1, fin2;
  t1 = h1;
  p1 = 0LL;
  while (t1 != a1 && p1 < 1000010) {
    t1 = (t1 * x1 + y1) % m;
    p1++;
  }
  if (p1 == 1000010) {
    cout << -1 << endl;
    return 0;
  }
  t2 = h2;
  p2 = 0LL;
  while (t2 != a2 && p2 < 1000010) {
    t2 = (t2 * x2 + y2) % m;
    p2++;
  }
  if (p2 == 1000010) {
    cout << -1 << endl;
    return 0;
  }
  if (p1 == p2) {
    cout << p1 << endl;
    return 0;
  }
  t1 = a1;
  u1 = 1LL;
  t1 = (t1 * x1 + y1) % m;
  while (t1 != a1 && u1 < 1000010) {
    t1 = (t1 * x1 + y1) % m;
    u1++;
  }
  if (u1 == 1000010) {
    cout << -1 << endl;
    return 0;
  }
  if (p1 + u1 == p2) {
    cout << p2 << endl;
    return 0;
  }
  t2 = a2;
  u2 = 1LL;
  t2 = (t2 * x2 + y2) % m;
  while (t2 != a2 && u2 < 1000010) {
    t2 = (t2 * x2 + y2) % m;
    u2++;
  }
  if (u2 == 1000010) {
    cout << -1 << endl;
    return 0;
  }
  fin1 = p1;
  fin2 = p2;
  int ctr = 0;
  while (fin1 != fin2 && ctr < 1000010 + 5) {
    while (fin1 < fin2 && ctr < 1000010 + 5) {
      fin1 += u1;
    }
    while (fin2 < fin1 && ctr < 1000010 + 5) {
      fin2 += u2;
    }
    ctr++;
  }
  if (ctr == 1000010 + 5) {
    cout << -1 << endl;
    return 0;
  } else
    cout << fin1 << endl;
  return 0;
}
