#include <bits/stdc++.h>
using namespace std;
const int SZ = 1000010, INF = 0x7FFFFFFF;
long long exgcd(long long a, long long b, long long &x, long long &y,
                long long &d) {
  if (b == 0) {
    x = 1;
    y = 0;
    d = a;
    return a;
  }
  long long gcd = exgcd(b, a % b, x, y, d);
  long long x2 = x, y2 = y;
  x = y2;
  y = x2 - (a / b) * y2;
  return gcd;
}
int main() {
  std::ios::sync_with_stdio(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;
  set<pair<long long, long long>> st;
  st.insert(make_pair(h1, h2));
  long long cnt1 = 0, cnt2 = 0, pri1 = 0, pri2 = 0, t1 = 0, t2 = 0;
  for (long long time = 1;; ++time) {
    long long newa1 = (x1 * h1 + y1) % m, newa2 = (x2 * h2 + y2) % m;
    if (newa1 == a1) {
      if (cnt1 == 0)
        pri1 = time;
      else if (cnt1 == 1)
        t1 = time - pri1;
      ++cnt1;
    }
    if (newa2 == a2) {
      if (cnt2 == 0)
        pri2 = time;
      else if (cnt2 == 1)
        t2 = time - pri2;
      ++cnt2;
    }
    if (pri1 && pri2 && t1 && t2) break;
    if (newa1 == a1 && newa2 == a2) {
      cout << time << endl;
      return 0;
    }
    if (time > 1e7) {
      cout << -1 << endl;
      return 0;
    }
    h1 = newa1, h2 = newa2;
  }
  long long x, y, d;
  exgcd(abs(t1), abs(t2), x, y, d);
  if (abs(pri1 - pri2) % d == 0) {
    x *= (pri2 - pri1) / d;
    y *= (pri2 - pri1) / d;
    y *= -1;
    if (x < 0) {
      int beishu = abs((x) / (t2 / d));
      x = x + beishu * abs(t2 / d);
      y = y + beishu * abs(t1 / d);
    }
    if (y < 0) {
      int num = 0;
      num = abs((y) / (t1 / d));
      y = y + num * abs(t1 / d);
      if (y < 0) {
        ++num;
        y += abs(t1 / d);
      }
      x += num * abs(t2 / d);
    }
    if (x < 0) x += abs(t2 / d);
    if (x > 0 && y > 0) {
      int num1 = abs((x) / (t2 / d));
      int num2 = abs((y) / (t1 / d));
      int miner = min(num1, num2);
      x -= miner * abs(t2 / d);
      y -= miner * abs(t1 / d);
    }
    cout << pri1 + x * t1 << endl;
  } else
    cout << -1 << endl;
  return 0;
}
