#include <bits/stdc++.h>
using namespace std;
int m;
long long h1, a1, x1, _y1;
long long h2, a2, x2, y2;
int main() {
  cin >> m;
  cin >> h1 >> a1 >> x1 >> _y1;
  cin >> h2 >> a2 >> x2 >> y2;
  long long second = 0;
  while (h1 != a1) {
    h1 = (x1 * h1 + _y1) % m;
    h2 = (x2 * h2 + y2) % m;
    second++;
    if (second > m + 1) {
      cout << "-1";
      return 0;
    }
  }
  if (h2 == a2) {
    cout << second;
    return 0;
  }
  long long sec_loop = 0;
  long long t_x2 = 1, t_y2 = 0;
  while (sec_loop == 0 || h1 != a1) {
    h1 = (x1 * h1 + _y1) % m;
    t_x2 = (t_x2 * x2) % m;
    t_y2 = (t_y2 * x2 + y2) % m;
    sec_loop++;
    if (sec_loop > m + 1) {
      cout << -1;
      return 0;
    }
  }
  long long cycle = 0;
  while (h2 != a2) {
    h2 = (h2 * t_x2 + t_y2) % m;
    cycle++;
    if (cycle > m + 1) {
      cout << -1;
      return 0;
    }
  }
  cout << second + sec_loop * cycle;
  return 0;
}
