#include <iostream>
using namespace std;

int main(){
	int a,b,c,d,e,f,r,x,y,z;
	while(cin >> a >> b >> c >> d >> e >> f, a){
		x = y = z = 1;
		r = 0;
		do{
			x = a*x%b;
			y = c*y%d;
			z = e*z%f;
			r++;
		}while(x != 1 || y != 1 || z != 1);
		cout << r << endl;
	}
}