#include <iostream>
using namespace std;

int main()
{
	int a[3];
	int m[3];
	while (true)
	{
		for (int i = 0; i < 3; i++) cin >> a[i] >> m[i];
		if (a[0] == 0 && a[1] == 0 && a[2] == 0 && m[0] == 0 && m[1] == 0 && m[2] == 0) return 0;

		int x = 1;
		int y = 1;
		int z = 1;
		int count = 0;
		while (true)
		{
			count++;
			x = (a[0] * x) % m[0];
			y = (a[1] * y) % m[1];
			z = (a[2] * z) % m[2];
			if (x == 1 && y == 1 && z == 1) break;
		}
		cout << count << endl;
	}

	return 0;
}