#include <bits/stdc++.h>
using namespace std;
const int maxn = 2000000 + 10;
bool vis[maxn];
long long a, a1, b, b1, c, d, xa, ya, xb, yb, ha, hb, m, t, p, q;
inline void cal() {
  ha = (xa * ha + ya) % m;
  hb = (xb * hb + yb) % m;
}
int main() {
  cin >> m >> a >> c >> xa >> ya >> b >> d >> xb >> yb;
  ha = a;
  hb = b;
  t = 0;
  while (ha != c && !vis[ha]) {
    vis[ha] = 1;
    cal();
    t++;
  }
  if (vis[ha]) {
    cout << -1 << endl;
    return 0;
  }
  if (hb == d) {
    cout << t << endl;
    return 0;
  }
  a1 = t;
  memset(vis, 0, sizeof(vis));
  cal();
  t++;
  p++;
  while (ha != c && !vis[ha]) {
    vis[ha] = 1;
    cal();
    t++;
    p++;
  }
  if (vis[ha]) {
    cout << -1 << endl;
    return 0;
  }
  if (hb == d) {
    cout << t << endl;
    return 0;
  }
  memset(vis, 0, sizeof(vis));
  ha = a;
  hb = b;
  t = 0;
  while (hb != d && !vis[hb]) {
    vis[hb] = 1;
    cal();
    t++;
  }
  if (vis[hb]) {
    cout << -1 << endl;
    return 0;
  }
  if (ha == c) {
    cout << t << endl;
    return 0;
  }
  b1 = t;
  memset(vis, 0, sizeof(vis));
  cal();
  t++;
  q++;
  while (hb != d && !vis[hb]) {
    vis[hb] = 1;
    cal();
    t++;
    q++;
  }
  if (vis[hb]) {
    cout << -1 << endl;
    return 0;
  }
  if (ha == c) {
    cout << t << endl;
    return 0;
  }
  memset(vis, 0, sizeof(vis));
  long long pos, ans, x, y;
  if (a1 < b1) {
    pos = ans = b1 - a1;
    x = q;
    y = p;
  } else {
    pos = ans = a1 - b1;
    x = p;
    y = q;
  }
  while (pos && !vis[pos]) {
    vis[pos] = 1;
    pos = (pos + x) % y;
    ans += x;
  }
  if (vis[pos]) {
    cout << -1 << endl;
    return 0;
  }
  cout << ans + min(a1, b1) << endl;
  return 0;
}
