#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
  ios_base::sync_with_stdio(false);
  cout.precision(10);
  cout << fixed;
  int m;
  scanf("%d", &m);
  int h1, a1, x1, y1;
  scanf("%d%d%d%d", &h1, &a1, &x1, &y1);
  int h2, a2, x2, y2;
  scanf("%d%d%d%d", &h2, &a2, &x2, &y2);
  ll t1 = 0, t2 = 0, c1 = 0, c2 = 0;
  for (int i = 0; i <= m; ++i) {
    ++t1;
    h1 = (1LL * x1 * h1 + y1) % m;
    if (h1 == a1) break;
  }
  if (h1 != a1) {
    cout << -1 << endl;
    return 0;
  };
  for (int i = 0; i <= m; ++i) {
    ++t2;
    h2 = (1LL * x2 * h2 + y2) % m;
    if (h2 == a2) break;
  }
  if (h2 != a2) {
    cout << -1 << endl;
    return 0;
  }
  for (int i = 0; i <= m; ++i) {
    ++c1;
    h1 = (1LL * x1 * h1 + y1) % m;
    if (h1 == a1) break;
  }
  for (int i = 0; i <= m; ++i) {
    ++c2;
    h2 = (1LL * x2 * h2 + y2) % m;
    if (h2 == a2) break;
  }
  if (c1 != m + 1) {
    while (t1 < t2) t1 += c1;
  }
  if (c2 != m + 1) {
    while (t2 < t1) t2 += c2;
  }
  if (t1 == t2) {
    cout << t1 << endl;
    return 0;
  }
  if (c1 == m + 1 || c2 == m + 1) {
    cout << -1 << endl;
    return 0;
  }
  for (int i = 0; i < 2 * max(c1, c2); ++i) {
    if (t1 < t2) t1 += c1;
    if (t2 < t1) t2 += c2;
    if (t2 == t1) {
      cout << t1 << endl;
      return 0;
    };
  }
  cout << -1 << endl;
  return 0;
}
