#include <stdio.h>
#include <vector>
#include <algorithm>
#include <stack>

using namespace std;

struct Data{
	long long int x,y,z;
};

int main(){
	long long int a1,a2,a3,m1,m2,m3,count;
	Data data;

	while(true){
		scanf("%lld %lld %lld %lld %lld %lld",&a1,&m1,&a2,&m2,&a3,&m3);
		if(a1 == 0 && m1 == 0 && a2 == 0 && m2 == 0 && m3 == 0 && m3 == 0)break;

		count = 0;
		data.x = 1;
		data.y = 1;
		data.z = 1;

		while(true){
			count++;
			data.x = a1*data.x%m1;
			data.y = a2*data.y%m2;
			data.z = a3*data.z%m3;

			if(data.x == 1 && data.y == 1 && data.z == 1)break;
		}

		printf("%lld\n",count);
	}


    return 0;
}