#include <bits/stdc++.h>
using namespace std;
int m;
vector<int> w1;
vector<int> w2;
int main() {
  scanf("%d", &(m));
  ;
  int(h1), (a1);
  scanf("%d%d", &(h1), &(a1));
  ;
  int(x1), (y1);
  scanf("%d%d", &(x1), &(y1));
  ;
  int(h2), (a2);
  scanf("%d%d", &(h2), &(a2));
  ;
  int(x2), (y2);
  scanf("%d%d", &(x2), &(y2));
  ;
  for (int i = (0); i < (2 * m + 1); ++i) {
    if (h1 == a1) w1.push_back(i);
    if (h2 == a2) w2.push_back(i);
    if (h1 == a1 && h2 == a2) {
      printf("%d\n", i);
      return 0;
    }
    h1 = ((h1 * 1LL * x1) + y1) % m;
    h2 = ((h2 * 1LL * x2) + y2) % m;
  }
  if (w1.size() < 2 || w2.size() < 2) {
    printf("-1\n");
    return 0;
  }
  int d1 = w1[1] - w1[0];
  int d2 = w2[1] - w2[0];
  int s1 = w1[0];
  int s2 = w2[0];
  for (int i = (0); i < (m + 1); ++i) {
    if (s1 + i * 1LL * d1 >= s2) {
      if ((s1 + i * 1LL * d1 - s2) % d2 == 0) {
        printf("%I64d\n", s1 + i * 1LL * d1);
        return 0;
      }
    }
  }
  printf("-1\n");
}
