#include <bits/stdc++.h>
using namespace std;
vector<int> res1;
vector<int> res2;
long long int m;
int main() {
  long long int h1, a1, x1, y1, h2, a2, x2, y2;
  scanf("%I64d", &m);
  scanf("%I64d%I64d", &h1, &a1);
  scanf("%I64d%I64d", &x1, &y1);
  scanf("%I64d%I64d", &h2, &a2);
  scanf("%I64d%I64d", &x2, &y2);
  long long int temp = 2 * m;
  for (int i = 0; i <= temp; i++) {
    if (h1 == a1) {
      res1.push_back(i);
    }
    if (h2 == a2) res2.push_back(i);
    h1 = (x1 * h1 % m + y1) % m;
    h2 = (x2 * h2 % m + y2) % m;
  }
  if (res1.empty() || res2.empty()) {
    printf("-1\n");
    return 0;
  }
  long long int t11 = res1[0], t21 = res2[0];
  long long int tt = 2 * m;
  long long int add1 = res1[1] - res1[0], add2 = res2[1] - res2[0];
  for (int i = 1; i <= tt; i++) {
    if (t11 == t21) {
      printf("%I64d\n", t11);
      return 0;
    }
    if (t11 < t21)
      t11 += add1;
    else if (t11 > t21)
      t21 += add2;
  }
  printf("-1\n");
}
