#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

unsigned long long int GCD(unsigned long long int x, unsigned long long int y)
{
	if(y == 0)
	{
		return(x);
	}
	else
	{
		GCD(y, x % y);
	}
}

void solve()
{
	int a1, m1, a2, m2, a3, m3;
	while(cin >> a1 >> m1 >> a2 >> m2 >> a3 >> m3, a1 || m1 || a2 || m2 || a3 || m3)
	{
		vector<unsigned long long int> count(3);
		int x = 1, y = 1, z = 1;
		do
		{
			x = (a1 * x) % m1;
			++count[0];
		}while(x != 1);

		do
		{
			y = (a2 * y) % m2;
			++count[1];
		}while(y != 1);
		
		do
		{
			z = (a3 * z) % m3;
			++count[2];
		}while(z != 1);
		sort(count.begin(), count.end());
		unsigned long long int gcd1 = GCD(count[2], count[1]);
		unsigned long long int lcm1 = count[2] * count[1] / gcd1;
		if(lcm1 < count[0])
		{
			unsigned long long int temp = lcm1;
			lcm1 = count[0];
			count[0] = temp;
		}
		unsigned long long int gcd2 = GCD(lcm1, count[0]);
		unsigned long long int lcm2 = lcm1 * count[0] / gcd2;
		cout << lcm2 << endl;
	}
}

int main()
{
	solve();
	return(0);
}