#include <bits/stdc++.h>
using namespace std;
int m;
long long h1, a1, poyo, hoge, h2, a2, kera, piyo;
void solve() {
  long long ans = 0;
  if (h1 == a1 && h2 == a2) {
    puts("0");
    return;
  }
  for (int i = 0; i < (int)m; ++i) {
    ++ans;
    h1 = (poyo * h1 + hoge) % m;
    h2 = (kera * h2 + piyo) % m;
    if (h1 == a1 && h2 == a2) {
      cout << ans << endl;
      return;
    }
  }
  for (int i = 0; i < (int)m; ++i) {
    if (h1 == a1) break;
    h1 = (poyo * h1 + hoge) % m;
    h2 = (kera * h2 + piyo) % m;
    ++ans;
  }
  if (h1 != a1) {
    puts("-1");
    return;
  }
  int cyc1 = 1;
  h1 = (poyo * h1 + hoge) % m;
  while (h1 != a1) {
    h1 = (poyo * h1 + hoge) % m;
    ++cyc1;
  }
  long long tmp = h2;
  vector<long long> v2;
  v2.push_back(tmp);
  h2 = (kera * h2 + piyo) % m;
  while (h2 != tmp) {
    v2.push_back(h2);
    h2 = (kera * h2 + piyo) % m;
  }
  int id = 0;
  for (int i = 0; i < (int)m; ++i) {
    if (v2[id] == a2) break;
    id = (id + cyc1) % (int)(v2).size();
    ans += cyc1;
  }
  if (v2[id] != a2) {
    puts("-1");
    return;
  }
  cout << ans << endl;
}
int main() {
  while (cin >> m) {
    cin >> h1 >> a1 >> poyo >> hoge >> h2 >> a2 >> kera >> piyo;
    solve();
  }
}
