#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
bool vis[1000005];
long long extend_gcd(long long a, long long b, long long &x, long long &y) {
  if (a == 0 && b == 0) return -1;
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  }
  long long d = extend_gcd(b, a % b, y, x);
  y -= a / b * x;
  return d;
}
int m;
int getans(long long h, int x, int y, int a) {
  memset(vis, 0, sizeof(vis));
  int c = 0;
  int mm = -1;
  vis[h] = 1;
  while (1) {
    h = (h * x + y) % m;
    c++;
    if (h == a) {
      mm = c;
      return mm;
    } else if (vis[h])
      return -1;
    else
      vis[h] = 1;
  }
}
int main(void) {
  long long h1, h2;
  long long f1, f2;
  long long a1, a2;
  int x1, x2;
  int y1, y2;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  int flag = 1;
  int n1 = 0, n2 = 0;
  int m1, m2;
  f1 = h1, f2 = h2;
  m1 = getans(h1, x1, y1, a1);
  if (m1 == -1) {
    printf("-1\n");
    return 0;
  }
  n1 = getans(a1, x1, y1, a1);
  m2 = getans(h2, x2, y2, a2);
  if (m2 == -1) {
    printf("-1\n");
    return 0;
  }
  n2 = getans(a2, x2, y2, a2);
  if (m1 == m2)
    printf("%d\n", m1);
  else if (n1 == -1 || n2 == -1) {
    long long cha = abs(m1 - m2);
    if (m1 > m2 && n2 != -1 && cha % n2 == 0) {
      printf("%d\n", m1);
      return 0;
    } else if (m2 > m1 && n1 != -1 && cha % n1 == 0) {
      printf("%d\n", m2);
      return 0;
    }
    printf("-1\n");
    return 0;
  } else {
    long long x, y;
    long long tgcd = extend_gcd(n1, -n2, x, y);
    long long b = m2 - m1;
    if ((b) % tgcd != 0) {
      printf("-1\n");
      return 0;
    }
    long long nd = b / tgcd;
    long long tn1 = n1;
    long long tn2 = n2;
    n1 /= tgcd;
    n2 /= tgcd;
    b /= tgcd;
    if (n1 < 0) n1 = -n1;
    if (n2 < 0) n2 = -n2;
    long long tx, ty;
    tx = (x * b % n2 + n2) % n2;
    ty = ((tn1 * tx + m1) - m2) / tn2;
    long long ans1 = (1LL << 60), ans2 = (1LL << 60);
    if (tx >= 0 && ty >= 0) ans1 = m1 + tx * tn1;
    ty = (y * b % n1 + n1) % n1;
    tx = ((tn2 * ty + m2) - m1) / tn1;
    if (tx >= 0 && ty >= 0) ans2 = m1 + tx * tn1;
    printf("%I64d\n", min(ans1, ans2));
  }
  return 0;
}
