#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<cmath>
#include<climits>
#include<vector>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;

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

long long lcm(long long a, long long b){
	return a*b / gcd(a, b);
}

long long f(long long x, long long a, long long m){
	if(x == 1) return 0;
	return f(a*x % m, a, m) + 1;
}

int main(){
	while(true){
		long long A, M, ans = 1;
		for(long long i = 0; i < 3; i++){
			cin >> A >> M;
			if(!A || !M) return 0;
			ans = lcm(ans, f( A % M, A, M ) + 1 );
		}
		printf("%d\n", ans);
	}
}