#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:16777216")
double eps = 1e-10;
using namespace std;
long long m, h1, a1, x_1, y_1, h2, a2, x_2, y_2, len1, len2, l1, l2, i1 = -1,
                                                                     i2 = -1;
int idx1[1000006], idx2[1000006], cycle1[1000006], cycle2[1000006];
bool check(long long x) {
  if (x < l2) {
    if (cycle2[x] == a2)
      return 1;
    else
      return 0;
  }
  x -= l2;
  x %= len2;
  return (cycle2[x + l2] == a2);
}
int main() {
  cin >> m >> h1 >> a1 >> x_1 >> y_1 >> h2 >> a2 >> x_2 >> y_2;
  for (int i = 0; i <= 1000000; i++) idx1[i] = idx2[i] = -1;
  idx1[h1] = 0, idx2[h2] = 0;
  cycle1[0] = h1, cycle2[0] = h2;
  for (int i = 1; i <= m + 1; i++) {
    int height = (x_1 * cycle1[i - 1] + y_1) % m;
    if (idx1[height] != -1) {
      len1 = i - idx1[height];
      l1 = idx1[height];
      break;
    } else {
      cycle1[i] = height;
      idx1[height] = i;
    }
  }
  for (int i = 1; i <= m + 1; i++) {
    int height = (x_2 * cycle2[i - 1] + y_2) % m;
    if (idx2[height] != -1) {
      len2 = i - idx2[height];
      l2 = idx2[height];
      break;
    } else {
      cycle2[i] = height;
      idx2[height] = i;
    }
  }
  for (int i = 0; i < l1; i++) {
    if (cycle1[i] == a1) {
      if (check(i)) {
        cout << i << endl;
      } else {
        puts("-1");
      }
      return 0;
    }
  }
  for (int i = l1; i < len1 + l1; i++) {
    if (cycle1[i] == a1) {
      i1 = i - l1;
      break;
    }
  }
  if (i1 == -1) {
    puts("-1");
    return 0;
  }
  for (int k1 = 0; k1 < 1000002; k1++) {
    long long t = l1 + (long long)k1 * len1 + i1;
    if (check(t)) {
      cout << t << endl;
      return 0;
    }
  }
  puts("-1");
}
