#include <bits/stdc++.h>
using namespace std;
int main() {
  long long m, h1, a1, x1, y1, h2, a2, x2, y2;
  scanf("%lld", &m);
  scanf("%lld%lld", &h1, &a1);
  scanf("%lld%lld", &x1, &y1);
  scanf("%lld%lld", &h2, &a2);
  scanf("%lld%lld", &x2, &y2);
  long long i;
  long long st1, st2, len1, len2;
  st1 = st2 = len1 = len2 = -1;
  for (i = 1; i <= 2 * m; i++) {
    h1 = (h1 * x1 + y1) % m;
    if (h1 == a1) {
      if (st1 == -1)
        st1 = i;
      else {
        if (len1 == -1) {
          len1 = i - st1;
        }
      }
    }
    h2 = (h2 * x2 + y2) % m;
    if (h2 == a2) {
      if (st2 == -1)
        st2 = i;
      else if (len2 == -1)
        len2 = i - st2;
    }
  }
  if (st2 == -1 || st1 == -1)
    printf("-1\n");
  else {
    if (st1 == st2)
      printf("%lld", st1);
    else {
      for (i = 1; i <= 2 * m; i++) {
        if (st1 < st2)
          st1 += len1;
        else if (st1 > st2)
          st2 += len2;
        if (st1 == st2) {
          printf("%lld\n", st1);
          return 0;
        }
      }
      printf("-1\n");
    }
  }
  return 0;
}
