#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long
#define rep2(x,from,to) for(int x=(from);x<(to);++(x))
#define rep(x,to) rep2(x,0,to)
ll gcd(ll a, ll b) {
	if(a < b) swap(a, b);
	while(b) {
		ll m = a / b;
		swap(a-=m*b, b);
	}
	return a;
}
ll lcm(ll a, ll b) {
	ll g = gcd(a, b);
	return a / g * b ;
}
int main() {
	int a1, m1, a2, m2, a3, m3;
	while(cin >> a1 >> m1 >> a2 >> m2 >> a3 >> m3 && (a1 || m1 || a2 || m2 || a3 || m3)) {
		ll a = 0, b = 0, c = 0;
		int x = 1, y = 1, z = 1;
		ll i = 1;
		while(1) {
			if(a == 0) x = (a1 * x) % m1;
			if(a == 0 && x == 1) a = i;
			if(b == 0) y = (a2 * y) % m2;
			if(b == 0 && y == 1) b = i;
			if(c == 0) z = (a3 * z) % m3;
			if(c == 0 && z == 1) c = i;
			i++;
			if(a != 0 && b != 0 && c != 0) {
				cout << lcm(a, lcm(b, c)) << endl;
				break;
			}
		}
	}
	return 0;
}