#include <stdio.h>
#include <iostream>

using namespace std;

int main(){
	int a[3],m[3];
	int counter;
	

	while (cin >> a[0] >> m[0] >> a[1] >> m[1] >> a[2] >> m[2]) {
		if (a[0] == 0 && a[1] == 0 && a[2] == 0 && m[0] == 0 && m[1] == 0 && m[2] == 0) {
			break;
		}
		counter = 0;
		int ichi[3] = {1,1,1}; 
		do {
			counter++;
			for (int i = 0; i < 3; i++) {
				ichi[i] = (a[i] * ichi[i]) % m[i];
			}
		}while (ichi[0] != 1 || ichi[1] != 1 || ichi[2] != 1);
		cout << counter << endl;
	}

}