#include <bits/stdc++.h>
using namespace std;
int main() {
  long long flag = 0;
  long long m, h1, h2, a1, a2, x1, x2, y1, y2, p1 = 0, r1 = 0, p2 = 0, r2 = 0;
  while (scanf("%I64d", &m) != EOF) {
    scanf("%I64d%I64d%I64d%I64d", &h1, &a1, &x1, &y1);
    scanf("%I64d%I64d%I64d%I64d", &h2, &a2, &x2, &y2);
    for (int i = 1; i <= 2 * m; i++) {
      h1 = (h1 * x1 + y1) % m;
      if (h1 == a1) {
        if (p1 == 0)
          p1 = i;
        else if (r1 == 0)
          r1 = i - p1;
      }
    }
    for (int i = 1; i <= 2 * m; i++) {
      h2 = (h2 * x2 + y2) % m;
      if (h2 == a2) {
        if (p2 == 0)
          p2 = i;
        else if (r2 == 0)
          r2 = i - p2;
      }
    }
    if (p1 == 0 || p2 == 0)
      printf("-1\n");
    else if (p1 == p2)
      printf("%I64d\n", p1);
    else {
      for (int i = 1; i <= 2 * m; i++) {
        if (p1 < p2)
          p1 += r1;
        else
          p2 += r2;
        if (p1 == p2) {
          printf("%I64d\n", p1);
          return 0;
        }
      }
      printf("-1\n");
    }
  }
  return 0;
}
