#include <bits/stdc++.h>
using namespace std;
int main() {
  int m, h1, a1, x1, y1, h2, a2, x2, y2, t1 = -1, t2 = -1, tt1 = -1, tt2 = -1;
  scanf("%d%d%d%d%d%d%d%d%d", &m, &h1, &a1, &x1, &y1, &h2, &a2, &x2, &y2);
  for (int i = 1; i <= m; i++) {
    h1 = ((long long)h1 * x1 + y1) % m;
    h2 = ((long long)h2 * x2 + y2) % m;
    if (h1 == a1 && tt1 == -1) tt1 = i;
    if (h2 == a2 && tt2 == -1) tt2 = i;
  }
  h1 = a1, h2 = a2;
  for (int i = 1; i <= m; i++) {
    h1 = ((long long)h1 * x1 + y1) % m;
    h2 = ((long long)h2 * x2 + y2) % m;
    if (h1 == a1 && t1 == -1) t1 = i;
    if (h2 == a2 && t2 == -1) t2 = i;
  }
  if (tt1 == -1 || tt2 == -1)
    puts("-1");
  else if (tt1 == tt2)
    printf("%d\n", tt1);
  else if (tt1 < tt2 && t1 != -1 && (tt2 - tt1) % t1 == 0)
    printf("%d\n", tt2);
  else if (tt1 > tt2 && t2 != -1 && (tt1 - tt2) % t2 == 0)
    printf("%d\n", tt1);
  else if (t1 == -1 || t2 == -1)
    puts("-1");
  else {
    long long a = tt1, ans = -1;
    for (int i = 0; i < m; i++) {
      if (a - tt2 >= 0 && (a - tt2) % t2 == 0) {
        ans = a;
        break;
      }
      a += t1;
    }
    printf("%I64d\n", ans);
  }
  return 0;
}
