#include <iostream>
using namespace std;

long long gcd(long long a, long long b){
	return b?gcd(b,(a%b)):a;
}

long long lcm(long long a, long long b){
	return a / gcd(a, b) * b;
}

int main(){
	int a, m;
	long long count[3];
	while(1){
		bool f = true;
		for(int i = 0;i < 3;i++){
			count[i] = 0;
			cin >> a >> m;
			if(!a && !m){f = false;break;}
			int x = 1;
			while(1){
				x = (a * x) % m;
				count[i]++;
				if(x == 1)break;
			}
		}
		if(f)cout << lcm(lcm(count[0], count[1]), count[2]) << endl;
		if(!f)break;
	}
	return 0;
}