#include <bits/stdc++.h>
#define int long long
using namespace std;
int h1, a1, x1, y, h2, a2, x2, y2, m;
void ch() {
cin >> m;
cin >> h1 >> a1 >> x1 >> y >> h2 >> a2 >> x2 >> y2;
bool f1 = 0, f2 = 0;
int t1 = 0;
for (int i = 1; i <= m; ++i) {
if (h1 == a1)
break;
t1++;
h1 = (x1 * h1 + y) % m;
}
if (h1 != a1) {
cout << -1 << '\n';
return;
}
int b1 = 0;
for (int i = 1; i <= m; i++) {
h1 = (x1 * h1 + y) % m;
b1++;
if (h1 == a1) {
f1 = 1;
break;
}
}
int t2 = 0;
for (int i = 1; i <= m; i++) {
if (h2 == a2)
break;
t2++;
h2 = (x2 * h2 + y2) % m;
}
if (h2 != a2) {
cout << -1 << '\n';
return;
}
int b2 = 0;
for (int i = 1; i <= m; i++) {
h2 = (x2 * h2 + y2) % m;
b2++;
if (h2 == a2) {
f2 = 1;
break;
}
}
if (f1) {
if (t1 < t2 && (t2 - t1) % b1 == 0) {
cout << t2 << "\n";
return;
}
}
if (f2) {
if (t1 > t2 && (t1 - t2) % b2 == 0) {
cout << t1 << endl;
return;
}
}
if (!f1 || !f2) {
cout << -1 << endl;
return;
}
for (int x = 0; x <= m; x++) {
if ((t1 + x * b1 - t2) % b2 == 0 && t1 + x * b1 - t2 >= 0) {
cout << t1 + x * b1 << "\n";
return;
}
}
cout << -1 << "\n";
return;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T;
cin >> T;
while (T--) ch();
return 0;
}