#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)
typedef long long ll;
int gcd(int a,int b){
	if(b==0)return a;
	return gcd(b,a%b);
}
int main(){
	ll a1,m1,a2,m2,a3,m3;
	while(1){
		ll cnt[3]={1,1,1};
		cin>>a1>>m1>>a2>>m2>>a3>>m3;
		if(a1==0&&m1==0)break;
		ll b1=a1,b2=a2,b3=a3;
		while(b1!=1){
			cnt[0]++;
			b1=b1*a1%m1;
		}
//		cout<<cnt[0]<<endl;
		while(b2!=1){
			cnt[1]++;
			b2=b2*a2%m2;
		}
		while(b3!=1){
			cnt[2]++;
			b3=b3*a3%m3;
		}
		sort(cnt,cnt+3);
		cnt[1]=cnt[1]*cnt[2]/gcd(cnt[2],cnt[1]);
		cout<<cnt[0]*cnt[1]/gcd(cnt[1],cnt[0])<<endl;
	}
}