// 0114
#include <iostream>
using namespace std;

int main(){
	while(1){
		int pos[3] = {1, 1, 1};
		int a[3], m[3];
		long long count = 0;

		cin>>a[0]>>m[0]>>a[1]>>m[1]>>a[2]>>m[2];
		if(a[0] == 0 && m[0] == 0 && a[1] == 0 && m[1] == 0 && a[2] == 0 && m[2] == 0)
			break;

		while(1){
			count++;
			for(int i=0;i<3;i++)
				pos[i] = a[i]*pos[i] % m[i];

			if(pos[0] == 1 && pos[1] == 1 && pos[2] == 1)
				break;
		}

		cout<<count<<endl;
	}
	return 0;
}