#include<stdio.h>
#include<string>
#include<stdlib.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<string.h>
#include<map>
#include<queue>

using namespace std;

typedef pair<int,int> pii;

#define rep(i,j) for(int i=0;i<(j);i++)
#define reps(i,j,k) for(int i=j;i<=k;i++)
#define in(i,j,k) ((i)>=(j)&&(i)<=(k))

long long gcd(long long x,long long y){
	if(y==0)return x;
	return gcd(y,x%y);
}

int main(){
	long long a[3],m[3],t[3],cnt,n;
	for(;;){
		rep(i,3)cin >> a[i] >> m[i];
		if(a[0]==0)break;
		rep(i,3){
			t[i]=1;
			cnt=0;
			do{
				t[i]=(a[i]*t[i])%m[i];
				cnt++;
			}while(t[i]!=1);
			t[i]=cnt;
		}
		rep(i,2){
			n=gcd(t[2],t[i]);
			t[2]=(t[2]/n)*t[i];
		}
		cout << t[2] << endl;
	}
	
	return 0;
}