#include <bits/stdc++.h>
using namespace std;
int main(int argc, char const* argv[]) {
  int m;
  long long h, a, x, y;
  long long H, A, X, Y;
  cin >> m;
  cin >> h >> a;
  cin >> x >> y;
  cin >> H >> A;
  cin >> X >> Y;
  long long time1 = 0;
  long long temp = h;
  while (h != a) {
    h = (x * h + y) % m;
    if (h == temp || time1 > m) {
      cout << -1 << endl;
      return 0;
    }
    time1++;
  }
  long long time2 = 0;
  long long temp2 = H;
  while (H != A) {
    H = (X * H + Y) % m;
    if (H == temp2 || time2 > m) {
      cout << -1 << endl;
      return 0;
    }
    time2++;
  }
  if (time1 == time2) {
    cout << time1 << endl;
    return 0;
  }
  long long alpha = 1;
  h = (x * h + y) % m;
  while (h != a) {
    h = (x * h + y) % m;
    if (alpha > m) {
      break;
    }
    alpha++;
  }
  long long beta = 1;
  H = (X * H + Y) % m;
  while (H != A) {
    H = (X * H + Y) % m;
    if (beta > m) {
      break;
    }
    beta++;
  }
  h = temp;
  H = temp2;
  if (alpha > m) {
    for (int i = 0; i < time1; i += 1) {
      temp2 = (temp2 * X + Y) % m;
    }
    if (temp2 == A) {
      cout << time1 << endl;
      return 0;
    } else {
      cout << -1 << endl;
      return 0;
    }
  } else if (beta > m) {
    for (int i = 0; i < time2; i += 1) {
      temp = (temp * x + y) % m;
    }
    if (temp == a) {
      cout << time2 << endl;
      return 0;
    } else {
      cout << -1 << endl;
      return 0;
    }
  }
  int i;
  for (i = 0; i < 2 * m + 1; i += 1) {
    long long x = i * beta + time2 - time1;
    if (x % alpha == 0 && x >= 0) {
      break;
    }
  }
  if (i == 2 * m + 1) {
    cout << -1 << endl;
  } else {
    cout << i * beta + time2 << endl;
  }
  return 0;
}
