#include <iostream>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;

int gcd(int a,int b)
{
	if(a%b == 0)
	{
		return b;
	}
	else
	{
		return gcd(b,a%b);
	}
}

int main()
{
	int a1,m1,a2,m2,a3,m3;
	while(cin >> a1 >> m1 >> a2 >> m2 >> a3 >> m3 && a1)
	{
		int x = 1,y = 1,z = 1;
		int count = 1;

		
		while(true)
		{
			int flag = 0;
			if((a1*x)%m1 == 1)
			{
				flag++;
			}
			if((a2*y)%m2 == 1)
			{
				flag++;
			}
			if((a3*z)%m3 == 1)
			{
				flag++;
			}

			if(flag == 3)
			{
				cout << count << endl;
				break;
			}
			else
			{
				count++;

				x = (a1*x) % m1;
				y = (a2*y) % m2;
				z = (a3*z) % m3;
			}
		}
	}
	return 0;
}