/*****include*****/
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
/*****デバッグ定義*****/
//#define DEBUG
/*****マクロ定義*****/
#define SIZE 1000
/*****名前空間*****/
using namespace std;

/*****グローバル変数置き場*****/
int a1,m1,a2,m2,a3,m3;
queue<int> task_x;
queue<int> task_y;
queue<int> task_z;
bool visited_x[SIZE];
bool visited_y[SIZE];
bool visited_z[SIZE];
/*****その他関数置き場*****/
int bfs(int x,int y,int z){
	int nx;int ny;int nz;
	//int x_next,y_next,z_next;
	long int cost = 0;
	/*task_x.push(x);task_y.push(y);task_z.push(z);
	cost++;
	visited_x[x] = true;visited_y[y] = true;visited_z[z] = true;
	while(!task_x.empty() && !task_x.empty() && !task_x.empty()){
		nx = task_x.front();task_x.pop();
		ny = task_y.front();task_y.pop();
		nz = task_z.front();task_z.pop();
		//cout << nx << " " << ny << " " << nz << " " << cost << endl;
		if(nx==1 && ny==1 && nz==1)	break;
		cost++;
		x_next = (a1 * nx) % m1;
		y_next = (a2 * ny) % m2;
		z_next = (a3 * nz) % m3;
		if(!(visited_x[x_next] && visited_y[y_next] && visited_z[z_next])){
			task_x.push(x_next);task_y.push(y_next);task_z.push(z_next);
			visited_x[x_next] = true;
			visited_y[y_next] = true;
			visited_z[z_next] = true;
		}
	}*/
	nx = x;ny = y;nz = z;
	cost++;
	while(1){
		nx = (a1 * nx) % m1;
		ny = (a2 * ny) % m2;
		nz = (a3 * nz) % m3;
		cost++;
		if(nx==1 && ny==1 && nz==1)	break;
	}
	return cost;
}
/*****main関数*****/
int main(){
	/*****変数置き場*****/
	long int root;
	/*****処理部*****/
	while(1){
		for(int i=0;i<SIZE;i++){
			visited_x[i] = false;
			visited_y[i] = false;
			visited_z[i] = false;
		}
		cin >> a1 >> m1 >> a2 >> m2 >> a3 >> m3;
		if(a1==0 && m1==0 && a2==0 && m2==0 && a3==0 && m3==0)	break;
		root = bfs(a1%m1,a2%m2,a3%m3);
		cout << root << endl;
	}
	/*****処理終了後*****/
	return 0;
}