#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

int main(){
	int x, y, z, flag, a[3], m[3];
	while (1){
		int x = 1, y = 1, z = 1, flag = 1;
		for (int i = 0; i < 3; i++){
			scanf("%d%d", &a[i], &m[i]);
			if (a[i] != 0 || m[i] != 0) flag = 0;
		}
		if (flag) break;
		int count = 0;
		while (1){
			x = (a[0]*x)%m[0];
			y = (a[1]*y)%m[1];
			z = (a[2]*z)%m[2];
			count++;
			if (x == 1 && y == 1 && z == 1) break;
		}
		cout <<  count << endl;
		
	}
	return 0;
}