#include <iostream>

using namespace std;
bool flag;
int a1,a2,a3,m1,m2,m3;
int x,y,z,cnt;
int main(){
	while(cin >> a1 >>m1 >>a2 >>m2 >>a3 >>m3){
		x=y=z=1;
		cnt=0;
		while(1){
			cnt++;
			x=(a1%m1*x)%m1;
			y=(a2%m2*y)%m2;
			z=(a3%m3*z)%m3;
			if(x==1&&y==1 &&z==1)break;
		}
		cout << cnt<<endl;
	}
	return 0;
}