#include <iostream>
#include <iomanip>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>

using namespace std;

int gcd(int a, int b) {
	if (a < b)
		swap(a, b);
	if (b == 0)
		return a;
	return gcd(b, a % b);
}

int main() {
	int a[3], m[3];
	while (1) {
		for (int i = 0; i < 3; i++) {
			cin >> a[i] >> m[i];
		}
		if (!a[0] && !m[0] && !a[1] && !m[1] && !a[2] && !m[2])
			break;
		long long ans = 0;
		int r[3];
		r[0] = r[1] = r[2] = 1;
		while (1) {
			ans++;
			for (int i = 0; i < 2; i++) {
				r[i] = (a[i] * r[i]) % m[i];
			}
			if (r[0] == 1 && r[1] == 1 && r[2] == 1)
				break;
		}
		cout << ans << endl;
	}
	
	return 0;
}