#include <bits/stdc++.h>
using namespace std;
inline long long mod(long long n) { return (n % 1000000007); }
long long gcd(long long a, long long b) {
  if (a == 0 || b == 0) return 0;
  if (b == 1)
    return b;
  else
    return gcd(b, a % b);
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long m;
  cin >> m;
  long long h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;
  long long start = h2;
  long long t1 = -1;
  long long cur = h1;
  cur %= m;
  for (long long i = 1; i <= m; i++) {
    cur = cur * x1 + y1;
    cur %= m;
    if (cur == a1) {
      t1 = i;
      break;
    }
  }
  if (t1 == -1) {
    cout << -1 << '\n';
    return 0;
  }
  h2 %= m;
  for (long long i = 1; i <= t1; i++) {
    h2 = h2 * x2 + y2;
    h2 %= m;
  }
  if (h2 == a2) {
    cout << t1 << '\n';
    return 0;
  }
  long long t2 = -1;
  cur = a1 * x1 + y1;
  cur %= m;
  if (cur == a1) {
    t2 = 1;
  } else {
    for (long long i = 2; i <= m; i++) {
      cur = cur * x1 + y1;
      cur %= m;
      if (cur == a1) {
        t2 = i;
        break;
      }
    }
  }
  if (t2 == -1) {
    cout << -1 << '\n';
    return 0;
  }
  long long a = 1, b = 0;
  for (long long i = 0; i < t2; i++) {
    a = a * x2;
    a %= m;
    b = b * x2 + y2;
    b %= m;
  }
  long long steps = -1;
  for (long long i = 1; i <= m; i++) {
    h2 = h2 * a + b;
    h2 %= m;
    if (h2 == a2) {
      steps = i;
      break;
    }
  }
  if (steps == -1) {
    cout << -1 << '\n';
    return 0;
  }
  cout << steps * t2 + t1 << '\n';
}
