#include <bits/stdc++.h>
using namespace std;
int main() {
  long long m, h1, a1, x1, y1, h2, a2, x2, y2, reach_a1 = 0, reach_a1_again = 0,
                                               cal, res = 0;
  cin >> m;
  cin >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;
  cal = h1;
  for (int i = 1; i <= m; i++) {
    cal = ((x1 * cal) % m + y1) % m;
    if (cal == a1) {
      reach_a1 = i;
      break;
    }
  }
  if (!reach_a1) {
    cout << -1;
    return 0;
  }
  cal = h2;
  for (int i = 1; i <= reach_a1; i++) cal = ((x2 * cal) % m + y2) % m;
  int height2_after_reach_a1 = cal;
  if (height2_after_reach_a1 == a2) {
    cout << reach_a1;
    return 0;
  }
  cal = a1;
  for (int i = 1; i <= m; i++) {
    cal = ((x1 * cal) % m + y1) % m;
    if (cal == a1) {
      reach_a1_again = i;
      break;
    }
  }
  if (!reach_a1_again) {
    cout << -1;
    return 0;
  }
  long long powx[m];
  powx[0] = 1;
  long long x = 1;
  for (int i = 0; i < reach_a1_again; i++) {
    x *= x2;
    x %= m;
    powx[i + 1] = x;
  }
  long long y = 0;
  for (int i = 0; i < reach_a1_again; i++) {
    y += powx[i];
    y %= m;
  }
  y *= y2;
  y %= m;
  cal = height2_after_reach_a1;
  for (int i = 1; i <= m; i++) {
    cal = ((x * cal) % m + y) % m;
    if (cal == a2) {
      res = reach_a1 + i * reach_a1_again;
      break;
    }
  }
  if (!res) {
    cout << -1;
    return 0;
  }
  cout << res;
  return 0;
}
