#include <bits/stdc++.h>
using namespace std;
long long xx, yy, mm, nn;
int main() {
  long long m, h1, h2, a1, a2, x1, x2, y1, y2;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  xx = yy = 0;
  while (h1 != a1) {
    if (xx > m) {
      cout << -1 << endl;
      return 0;
    }
    h1 = (h1 * x1 + y1) % m;
    ++xx;
  }
  while (h2 != a2) {
    if (yy > m) {
      cout << -1 << endl;
      return 0;
    }
    h2 = (h2 * x2 + y2) % m;
    ++yy;
  }
  if (xx == yy) {
    cout << xx << endl;
    return 0;
  }
  mm = nn = 1;
  h1 = (h1 * x1 + y1) % m;
  h2 = (h2 * x2 + y2) % m;
  while (h1 != a1) {
    if (mm > m) {
      mm = -1;
      break;
    }
    h1 = (h1 * x1 + y1) % m;
    ++mm;
  }
  while (h2 != a2) {
    if (nn > m) {
      nn = -1;
      break;
    }
    h2 = (h2 * x2 + y2) % m;
    ++nn;
  }
  if (mm == -1 && nn == -1) {
    cout << -1 << endl;
    return 0;
  }
  if (mm == -1) {
    while (yy < xx) yy += nn;
    if (xx == yy) {
      cout << xx << endl;
      return 0;
    } else {
      cout << -1 << endl;
      return 0;
    }
  }
  if (nn == -1) {
    while (xx < yy) xx += mm;
    if (xx == yy) {
      cout << xx << endl;
      return 0;
    } else {
      cout << -1 << endl;
      return 0;
    }
  }
  if (yy > xx) {
    swap(xx, yy);
    swap(mm, nn);
  }
  yy %= nn;
  int aux = 0;
  while (1) {
    if (aux > nn) {
      cout << -1 << endl;
      return 0;
    }
    if (xx % nn == yy) {
      cout << xx << endl;
      return 0;
    }
    xx += mm;
    ++aux;
  }
  return 0;
}
