#include <bits/stdc++.h>
using namespace std;
const int fx[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
const int fxx[8][2] = {{0, 1}, {0, -1}, {1, 0},  {-1, 0},
                       {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
int H1, A1, X1, Y1, H2, A2, X2, Y2, M;
int pos1, rep1, pos2;
bool flag;
long long ans;
int ex() {
  printf("-1\n");
  return 0;
}
int main() {
  scanf("%d", &M);
  scanf("%d", &H1);
  scanf("%d", &A1);
  scanf("%d", &X1);
  scanf("%d", &Y1);
  scanf("%d", &H2);
  scanf("%d", &A2);
  scanf("%d", &X2);
  scanf("%d", &Y2);
  pos1 = 0;
  while (pos1 <= M && H1 != A1) {
    H1 = (1LL * H1 * X1 + Y1) % M;
    pos1++;
  }
  if (pos1 == M + 1) return ex();
  int t = pos1;
  while (t--) {
    H2 = (1LL * H2 * X2 + Y2) % M;
  }
  if (H2 == A2) {
    ans = pos1;
    printf("%lld\n", ans);
    return 0;
  }
  rep1 = 1;
  H1 = (1LL * H1 * X1 + Y1) % M;
  while (H1 != A1 && rep1 <= M) {
    H1 = (1LL * H1 * X1 + Y1) % M;
    rep1++;
  }
  if (rep1 == M + 1) return ex();
  int c = 1, d = 0;
  for (int i = 1; i < rep1 + 1; i++) {
    c = (1LL * c * X2) % M;
    d = (1LL * d * X2 + Y2) % M;
  }
  int pos2 = 0;
  while (pos2 <= M && H2 != A2) {
    H2 = (1LL * H2 * c + d) % M;
    pos2++;
  }
  if (pos2 == M + 1)
    return ex();
  else {
    ans = 1LL * rep1 * pos2 + pos1;
    printf("%lld\n", ans);
    return 0;
  }
  return 0;
}
