#include <bits/stdc++.h>
using namespace std;
const int maxN = 2 * 1000 * 1000;
long long oneC, oneT, twoC, twoT, facO, facT, termO, termT, m,
    transitionsO[maxN + 5], transitionsT[maxN + 5], intialO, intialT, cycleO,
    cycleT;
int main(void) {
  cin >> m >> oneC >> oneT >> facO >> termO >> twoC >> twoT >> facT >> termT;
  for (int(i) = (0); i <= (int)(m - 1); (i)++) {
    transitionsO[i] = (i * facO + termO) % m;
    transitionsT[i] = (i * facT + termT) % m;
  }
  int stepsOne = 0;
  while (stepsOne < maxN && oneC != oneT) oneC = transitionsO[oneC], stepsOne++;
  if (oneC != oneT) {
    cout << -1;
    return 0;
  }
  int stepsTwo = 0;
  while (stepsTwo < maxN && twoC != twoT) twoC = transitionsT[twoC], stepsTwo++;
  if (twoC != twoT) {
    cout << -1;
    return 0;
  }
  intialO = stepsOne;
  intialT = stepsTwo;
  if (stepsOne < stepsTwo) {
    while (stepsOne != stepsTwo) oneC = transitionsO[oneC], stepsOne++;
  }
  if (stepsTwo < stepsOne) {
    while (stepsOne != stepsTwo) twoC = transitionsT[twoC], stepsTwo++;
  }
  if (oneC == oneT && twoC == twoT) {
    printf("%d", stepsOne);
    exit(0);
  }
  oneC = transitionsO[oneT];
  cycleO = 1;
  while (oneC != oneT && cycleO < maxN) {
    oneC = transitionsO[oneC];
    cycleO++;
  }
  twoC = transitionsT[twoT];
  cycleT = 1;
  while (twoC != twoT && cycleT < maxN) {
    twoC = transitionsT[twoC];
    cycleT++;
  }
  if (cycleO == maxN || cycleT == maxN) {
    cout << -1;
    exit(0);
  }
  for (int(i) = (1); i <= (int)(maxN); (i)++) {
    long long temp = i * cycleO + intialO - intialT;
    if (temp % cycleT == 0) {
      cout << temp + intialT;
      exit(0);
    }
  }
  cout << -1;
}
