#include <bits/stdc++.h>
using namespace std;
int main() {
  long long m, h1, a1, x1, y1, h2, a2, x2, y2;
  long long p1, p2, q1, q2;
  while (cin >> m >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2) {
    p1 = p2 = q1 = q2 = 0;
    for (long long i = 1; i <= 2 * m; i++) {
      h1 = (h1 * x1 + y1) % m;
      if (h1 == a1) {
        if (p1 == 0)
          p1 = i;
        else if (q1 == 0) {
          q1 = i - p1;
          break;
        }
      }
    }
    for (long long i = 1; i <= 2 * m; i++) {
      h2 = (h2 * x2 + y2) % m;
      if (h2 == a2) {
        if (p2 == 0)
          p2 = i;
        else if (q2 == 0) {
          q2 = i - p2;
          break;
        }
      }
    }
    if (p1 == 0 || p2 == 0) {
      puts("-1");
      continue;
    }
    long long ans1 = p1, ans2 = p2;
    long long i;
    for (i = 1; i <= 2 * m; i++) {
      if (ans1 == ans2) {
        printf("%I64d\n", ans1);
        break;
      }
      if (ans1 > ans2) {
        ans2 += q2;
      }
      if (ans1 < ans2) {
        ans1 += q1;
      }
    }
    if (i > 2 * m) {
      puts("-1");
    }
  }
  return 0;
}
