#include <iostream>
using namespace std;


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