#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int m, h1, a1, x1, y1, h2, a2, x2, y2;
  cin >> m >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;
  vector<long long int> frog(m, -1);
  vector<long long int> flower(m, -1);
  long long int fr = h1 % m;
  long long int times = 0;
  while (frog[fr] == -1) {
    frog[fr] = times++;
    fr = (fr * x1 + y1) % m;
  }
  long long int rfr = times - frog[fr];
  long long int timel = 0;
  long long int fl = h2 % m;
  while (flower[fl] == -1) {
    flower[fl] = timel++;
    fl = (fl * x2 + y2) % m;
  }
  long long int rfl = timel - flower[fl];
  if (frog[a1] == -1 || flower[a2] == -1) {
    cout << -1 << endl;
    return 0;
  }
  if (frog[a1] < times - rfr && flower[a2] < timel - rfl) {
    if (frog[a1] == flower[a2]) {
      cout << frog[a1];
      return 0;
    } else {
      cout << -1;
      return 0;
    }
  }
  if (frog[a1] < times - rfr) {
    for (int i = 0; i < timel; i++) {
      if (frog[a1] == flower[a2] + i * rfl) {
        cout << frog[a1];
        return 0;
      }
      if (i == timel - 1) {
        cout << -1;
        return 0;
      }
    }
  }
  if (flower[a2] < timel - rfl) {
    for (int i = 0; i < times; i++) {
      if (flower[a2] == frog[a1] + i * rfr) {
        cout << flower[a2];
        return 0;
      }
      if (i == timel - 1) {
        cout << -1;
        return 0;
      }
    }
  }
  long long int ans = 10000000000000;
  long long int flag1 = frog[a1];
  for (long long int i = 0; i < timel; i++) {
    if (flag1 - flower[a2] >= 0 && (flag1 - flower[a2]) % rfl == 0) {
      ans = min(ans, flag1);
      break;
    } else {
      flag1 += rfr;
    }
  }
  long long int flag2 = flower[a2];
  for (long long int i = 0; i < times; i++) {
    if (flag2 - frog[a1] >= 0 && (flag2 - frog[a1]) % rfr == 0) {
      ans = min(ans, flag2);
      break;
    } else {
      flag2 += rfl;
    }
  }
  if (ans == 10000000000000) {
    cout << -1 << endl;
  } else {
    cout << ans << endl;
  }
}
