#include <bits/stdc++.h>
#pragma warning(disable : 4786)
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e6 + 5;
int vis[maxn];
long long ex_gcd(long long a, long long b, long long &x, long long &y) {
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  }
  long long d = ex_gcd(b, a % b, y, x);
  y = y - a / b * x;
  return d;
}
long long linearmod(long long a, long long b, long long c) {
  long long x, y;
  long long d = ex_gcd(a, c, x, y);
  if (b % d) return -1;
  x = b / d * x;
  long long m = c / d;
  return (x % m + m) % m;
}
int main() {
  long long h1, h2, a1, a2, x1, x2, y1, y2, m, H1, H2;
  scanf("%lld", &m);
  scanf("%lld%lld%lld%lld", &h1, &a1, &x1, &y1);
  scanf("%lld%lld%lld%lld", &h2, &a2, &x2, &y2);
  memset(vis, 0, sizeof(vis));
  H1 = h1;
  H2 = h2;
  long long s1, s2, dis1 = 0, dis2 = 0;
  bool ok1 = 0, ok2 = 0;
  long long times1 = 0, times2 = 0;
  vis[H1 % m] = 1;
  for (int i = 1; i <= 2 * m; i++) {
    H1 = (x1 * H1 % m + y1) % m;
    if (!vis[H1])
      vis[H1] = i + 1;
    else {
      if (vis[a1] && vis[H1] <= vis[a1] && vis[a1] < i + 1) {
        s1 = vis[a1] - 1;
        dis1 = i + 1 - vis[H1];
        times1 = vis[a1] - 1;
        ok1 = 1;
      } else if (vis[a1] && !(vis[H1] <= vis[a1] && vis[a1] < i + 1)) {
        times1 = vis[a1] - 1;
      }
      break;
    }
  }
  memset(vis, 0, sizeof(vis));
  vis[H2 % m] = 1;
  for (int i = 1; i <= 2 * m; i++) {
    H2 = (x2 * H2 % m + y2) % m;
    if (!vis[H2])
      vis[H2] = i + 1;
    else {
      if (vis[a2] && vis[H2] <= vis[a2] && vis[a2] < i + 1) {
        s2 = vis[a2] - 1;
        dis2 = i + 1 - vis[H2];
        times2 = vis[a2] - 1;
        ok2 = 1;
      } else if (vis[a2] && !(vis[H2] <= vis[a2] && vis[a2] < i + 1)) {
        times2 = vis[a2] - 1;
      }
      break;
    }
  }
  if (!times1 || !times2) {
    printf("-1\n");
  } else if (ok1 && ok2) {
    long long ans = linearmod(dis2, s1 - s2, dis1);
    if (ans != -1)
      printf("%lld\n", s2 + ans * dis2);
    else
      printf("-1\n");
  } else if (!ok1 && ok2) {
    if (times1 < s2)
      printf("-1\n");
    else if ((times1 - s2) % dis2 == 0)
      printf("%lld\n", times1);
    else
      printf("-1\n");
  } else if (ok1 && !ok2) {
    if (times2 < s1)
      printf("-1\n");
    else if ((times2 - s1) % dis1 == 0)
      printf("%lld\n", times2);
    else
      printf("-1\n");
  } else {
    printf("-1\n");
  }
  return 0;
}
