#include <iostream>
#include <map>
#include <string>
#include <cstdio>
using namespace std;

int main() {
	int a1,a2,a3,m1,m2,m3;
	int x,y,z;
	int cnt;
	
	while(cin>>a1>>m1>>a2>>m2>>a3>>m3, a1|a2|a3|m1|m2|m3){
		x=y=z=1;
		cnt=0;
		
		do{
			x = (a1*x) % m1;
			y = (a2*y) % m2;
			z = (a3*z) % m3;
			++cnt;
		}while(x-1 || y-1 || z-1);
		
		cout << cnt << endl;
	}
	return 0;
}