#include <bits/stdc++.h>   using namespace std;   const int MOD = 1e9 + 7;   const int SIZE = 1e6 + 10;   using namespace std;   int main() {     long long m, h1, a1, x1, y1, h2, a2, x2, y2;     cin >> m >> h1 >> a1 >> x1 >> y1 >> h2 >> a2 >> x2 >> y2;     long long res1 = 0, per1 = 0, now = h1, now3 = h1, now4 = h2, p = 0;     for (int i = 0; i < (20000000); ++i) {       now = (now * x1 + y1) % m;       res1++;       if (now == a1)         break;       else if (i == 19999999) {         cout << -1;         return 0;       }     }     for (int i = 0; i < (10000000); ++i) {       now3 = (now3 * x1 + y1) % m;       now4 = (now4 * x2 + y2) % m;       p++;       if (now3 == a1 && now4 == a2) {         cout << p;         return 0;       }     }     for (int i = 0; i < (20000000); ++i) {       now = (now * x1 + y1) % m;       per1++;       if (now == a1) break;     }     long long res2 = 0, per2 = 0, now2 = h2;     for (int i = 0; i < (9999999); ++i) {       now2 = (now2 * x2 + y2) % m;       res2++;       if (now2 == a2)         break;       else if (i == 9999998) {         cout << -1;         return 0;       }     }     for (int i = 0; i < (20000000); ++i) {       now2 = (now2 * x2 + y2) % m;       per2++;       if (now2 == a2) break;     }     for (int i = 0; i < (2000000); ++i) {       if (res1 == res2) {         cout << res1;         return 0;       }       if (res1 > res2)         res2 += per2;       else if (res2 > res1)         res1 += per1;     }     cout << -1;   }   