#include <bits/stdc++.h>
using namespace std;
long long const inf = 1e18;
long long c1, c2;
long long arr1[1000100], arr2[1000100];
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) {
    return false;
  }
  x0 *= c / g;
  y0 *= c / g;
  if (a < 0) x0 = -x0;
  if (b < 0) y0 = -y0;
  return true;
}
void shift_solution(long long &x, long long &y, long long a, long long b,
                    long long cnt) {
  x += cnt * b;
  y -= cnt * a;
}
long long find_all_solutions(long long a, long long b, long long c) {
  long long x, y, g;
  if (!find_any_solution(a, b, c, x, y, g)) return inf;
  a /= g;
  b /= g;
  long long Min = inf;
  long long sign_a = a > 0 ? +1 : -1;
  long long sign_b = b > 0 ? +1 : -1;
  shift_solution(x, y, a, b, -x / b);
  if (x < 0) shift_solution(x, y, a, b, sign_b);
  shift_solution(x, y, a, b, y / a);
  if (y < 0) shift_solution(x, y, a, b, -sign_a);
  if (x >= 0 && y >= 0) {
    Min = a * x + c1;
  }
  return Min;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long m, h1, h2, a1, a2, x1, x2, y1, y2;
  cin >> m;
  cin >> h1 >> a1;
  cin >> x1 >> y1;
  cin >> h2 >> a2;
  cin >> x2 >> y2;
  int now1 = h1, now2 = h2, now;
  for (int i = 0; i <= m; i++) {
    arr1[i] = now1;
    arr2[i] = now2;
    now1 = (x1 * now1 + y1) % m;
    now2 = (x2 * now2 + y2) % m;
  }
  for (int i = 0; i <= m; i++) {
    if (arr1[i] == a1 && arr2[i] == a2) {
      cout << i << "\n";
      return 0;
    }
  }
  bool flag = false;
  for (int i = 0; i <= m; i++) {
    if (arr1[i] == a1) {
      c1 = i;
      flag = true;
      break;
    }
  }
  if (!flag) {
    cout << "-1\n";
    return 0;
  }
  flag = false;
  for (int i = 0; i <= m; i++) {
    if (arr2[i] == a2) {
      c2 = i;
      flag = true;
      break;
    }
  }
  if (!flag) {
    cout << "-1\n";
    return 0;
  }
  now = (a1 * x1 + y1) % m;
  flag = false;
  int a;
  for (int i = 1; i <= m; i++) {
    if (now == a1) {
      a = i;
      flag = true;
      break;
    }
    now = (now * x1 + y1) % m;
  }
  if (!flag) {
    cout << "-1\n";
    return 0;
  }
  now = (a2 * x2 + y2) % m;
  int b;
  flag = false;
  for (int i = 1; i <= m; i++) {
    if (now == a2) {
      b = i;
      flag = true;
      break;
    }
    now = (now * x2 + y2) % m;
  }
  if (!flag) {
    cout << "-1\n";
    return 0;
  }
  long long c = c2 - c1;
  long long ans = find_all_solutions(a, -b, c);
  if (ans == inf) {
    cout << "-1\n";
  } else {
    cout << ans << "\n";
  }
}
