#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>

#define mp       make_pair
#define pb       push_back
#define all(x)   (x).begin(),(x).end()
#define rep(i,n) for(int i=0;i<(n);i++)
#define repi(i,a,b) for(int i = (a); i < (b); i++)

using namespace std;

typedef    long long          ll;
typedef    unsigned long long ull;
typedef    vector<bool>       vb;
typedef    vector<int>        vi;
typedef    vector<vb>         vvb;
typedef    vector<vi>         vvi;
typedef    pair<int,int>      pii;

const int INF=1<<29;
const double EPS=1e-9;

const int dx[]={1,0,-1,0},dy[]={0,-1,0,1};

int main(){
	int a[3];
	int m[3];
	bool flag =true;
	while(flag){
		int x,y,z;
		x =y=z=1;
		int cnt = 0;
		int sum =0;
		for(int i =0;i <3;i++){
			cin>>a[i];
			cin>>m[i];
			if(a[i]!=0||m[i]!=0){
				sum=1;
			}
		}
		while(true){
			if(sum==0){
				flag=false;
				break;
			}
			x =(a[0]*x)%m[0];
			y =(a[1]*y)%m[1];
			z =(a[2]*z)%m[2];
			cnt++;
			//cout <<"test"<<endl;
			if(x==1&&x==y&&x==z){
				cout <<cnt<<endl;
				break;
			}
		}
		
	}
	return 0;
}