#include <iostream>
using namespace std;
int main()
{
	int a[3], m[3], x, y, z, n;
	while (cin >> a[0] >> m[0] >> a[1] >> m[1] >> a[2] >> m[2])
	{
		if (!a[0] && !m[0] && !a[1] && !m[1] && !a[2] && !m[2])
			break;
		x = y = z = 1, n = 0;
		do {
			x = (a[0]*x)%m[0];
			y = (a[1]*y)%m[1];
			z = (a[2]*z)%m[2];
			n++;
		} while (x != 1 || y != 1 || z != 1);
		cout << n << endl;
	}
}