#include <bits/stdc++.h>
using namespace std;
template <typename _Ty>
_Ty sq(_Ty k) {
  return k * k;
}
long long gcd(long long a, long long b, long long& x, long long& y) {
  if (a == 0) {
    x = 0;
    y = 1;
    return b;
  }
  long long x1, y1;
  long long d = gcd(b % a, a, x1, y1);
  x = y1 - (b / a) * x1;
  y = x1;
  return d;
}
bool find_any_solution(long long a, long long b, long long c, long long& x0,
                       long long& y0, long long& g) {
  g = gcd(abs(a), abs(b), x0, y0);
  if (c % g != 0) return false;
  x0 *= c / g;
  y0 *= c / g;
  if (a < 0) x0 *= -1;
  if (b < 0) y0 *= -1;
  return true;
}
int main() {
  long long m;
  scanf("%lld", &m);
  vector<long long> step1(m, -1), step2(m, -1);
  long long h1, a1;
  scanf("%lld%lld", &h1, &a1);
  long long x1, y1;
  scanf("%lld%lld", &x1, &y1);
  long long h2, a2;
  scanf("%lld%lld", &h2, &a2);
  long long x2, y2;
  scanf("%lld%lld", &x2, &y2);
  step1[h1] = 0;
  long long cur = (x1 * h1 + y1) % m;
  long long curstep = 1;
  while (step1[cur] == -1) {
    step1[cur] = curstep;
    curstep++;
    cur = (x1 * cur + y1) % m;
    ((void)0);
  }
  long long s1 = step1[cur];
  long long l1 = curstep - step1[cur];
  ((void)0);
  step2[h2] = 0;
  cur = (x2 * h2 + y2) % m;
  curstep = 1;
  while (step2[cur] == -1) {
    step2[cur] = curstep;
    curstep++;
    cur = (x2 * cur + y2) % m;
    ((void)0);
  }
  long long s2 = step2[cur];
  long long l2 = curstep - step2[cur];
  long long c1 = step1[a1], c2 = step2[a2];
  if (c1 == -1 || c2 == -1) {
    puts("-1");
    return 0;
  }
  if (c1 < s1 && c2 < s2) {
    if (c1 == c2)
      printf("%lld", c1);
    else
      puts("-1");
    return 0;
  }
  if (c1 < s1) {
    if (c1 >= c2 && ((c1 - c2) % l2 == 0))
      printf("%lld", c1);
    else
      puts("-1");
    return 0;
  }
  if (c2 < s2) {
    if (c2 >= c1 && ((c2 - c1) % l1 == 0))
      printf("%lld", c2);
    else
      puts("-1");
    return 0;
  }
  ((void)0);
  ((void)0);
  ((void)0);
  ((void)0);
  ((void)0);
  long long a = l1, b = -l2, c = c2 - c1;
  long long x0, y0, g;
  if (!find_any_solution(a, b, c, x0, y0, g)) {
    puts("-1");
    return 0;
  }
  ((void)0);
  ((void)0);
  ((void)0);
  long long k = y0 / (a / g);
  if (y0 < 0) k--;
  long long x = x0 + k * b / g;
  if (x < 0) {
    k = x0 / (b / g);
    if (x0 < 0) k--;
  }
  x = x0 + k * b / g;
  long long y = y0 - k * a / g;
  ((void)0);
  ((void)0);
  ((void)0);
  ((void)0);
  printf("%lld", c1 + l1 * (x0 + k * b / g));
  return 0;
}
