#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
const int N = 1e6 + 6;
int m;
int vis[N], vid;
int main() {
  scanf("%d", &m);
  int h1, a1, x1, y1, h2, a2, x2, y2;
  scanf("%d %d %d %d %d %d %d %d", &h1, &a1, &x1, &y1, &h2, &a2, &x2, &y2);
  long long ans = 0;
  for (int i = 0; i <= 1000000; ++i) {
    if (h1 == a1 && h2 == a2) {
      printf("%d", i);
      return 0;
    }
    h1 = (1ll * h1 * x1 + y1) % m;
    h2 = (1ll * h2 * x2 + y2) % m;
    ++ans;
  }
  deque<int> c1, c2;
  int v1 = h1, v2 = h2;
  ++vid;
  while (vis[v1] != vid) {
    vis[v1] = vid;
    c1.push_back(v1);
    v1 = (1ll * v1 * x1 + y1) % m;
  }
  if (vis[a1] != vid) {
    puts("-1");
    return 0;
  }
  ++vid;
  while (vis[v2] != vid) {
    vis[v2] = vid;
    c2.push_back(v2);
    v2 = (1ll * v2 * x2 + y2) % m;
  }
  if (vis[a2] != vid) {
    puts("-1");
    return 0;
  }
  if (c1.size() > c2.size()) {
    c1.swap(c2);
    swap(h1, h2);
    swap(a1, a2);
    swap(x1, x2);
    swap(y1, y2);
  }
  while (c1[0] != a1) {
    ++ans;
    c1.push_back(c1[0]);
    c1.pop_front();
    c2.push_back(c2[0]);
    c2.pop_front();
  }
  ++vid;
  int s1 = c1.size(), s2 = c2.size();
  int cur = 0;
  while (vis[cur] != vid) {
    vis[cur] = vid;
    if (c2[cur] == a2) {
      printf("%lld", ans);
      return 0;
    }
    cur = (cur + s1) % s2;
    ans += s1;
  }
  puts("-1");
}
