#include <iostream>
#include <cstdio>

int main(){
	while(1){
		int a[3], m[3], p[3];
		
		for(int i=0; i<3; ++i)
			scanf(" %d %d", &a[i], &m[i]);
	
		if(a[0]==0 && m[0]==0) break;

		for(int i=0; i<3; ++i)
			p[i] = a[i]%m[i];
		long count=1;
	
		while(1){
			if(p[0]==1 && p[1]==1 && p[2]==1) break;
		
			for(int i=0; i<3; ++i)
				p[i] = (a[i]*p[i]) % m[i];
			
			++count;
		}
		
		printf("%ld\n", count);	
	}

	return 0;
}