#include <stdio.h>
int main(){
	int xyz[3],a[3],m[3];
	while(1){
		int count=0;
		for(int i=0;i<3;i++){
			scanf("%d%d",&a[i],&m[i]);
			xyz[i]=1;
		}
		if(!a[0]&&!a[1]&&!a[2]&&!m[0]&&!m[1]&&!m[2]) break;
		while(1){
			for(int i=0;i<3;i++) xyz[i] = (a[i]*xyz[i])%m[i];
			count++;
			if(xyz[0]==1&&xyz[1]==1&&xyz[2]==1) break;
		}
		printf("%d\n",count);
	}
	return 0;
}