#include #include #include using namespace std; string tos(vector &a) { return to_string(a[0])+","+to_string(a[1])+","+to_string(a[2])+","+to_string(a[3]); } void mul(vector &a, vector &c, long long p) { vector d(4); d[0] = (a[0] * c[0] % p + a[1] * c[2] % p) % p; d[1] = (a[0] * c[1] % p + a[1] * c[3] % p) % p; d[2] = (c[0] * a[2] % p + c[2] * a[3] % p) % p; d[3] = (c[1] * a[2] % p + c[3] * a[3] % p) % p; a = d; } void modpow(vector &a, long long k, long long p) { if (k > 1) { if (k&1) { vector c(a); modpow(a, k-1, p); mul(a, c, p); } else { mul(a, a, p); modpow(a, k/2, p); } } } int main() { long long p; vector a(4), b(4); cin >> p; for (int i = 0; i < 4; i++) cin >> a[i]; for (int i = 0; i < 4; i++) cin >> b[i]; if (a == b) { cout << 1 << endl; return 0; } vector c(a); vector> s1; s1.push_back(a); vector e(a), f(b); modpow(e, p-2, p); unordered_map s2; for (int i=1; i <= 1e5; i++) { mul(a, c, p); s1.push_back(a); mul(f, e, p); s2[tos(f)] = i; if (a == b) { cout << (i+1) << endl; return 0; } if (a == c) { cout << (-1) << endl; return 0; } // cout << a[0] << "," << a[1] << "," << a[2] << "," << a[3] << endl; } for (int i = 0; i < s1.size(); i++) { auto y = s2.find(tos(s1[i])); if (y != s2.end()) { cout << ((i+1)*y->second) << endl; return 0; } } cout << (-1) << endl; return 0; }