#include <cstdio>
#include <algorithm>
#include <map>

const long long int INF = 1001001001001001LL;

long long int gcd(long long int a, long long int b) {
    if(a < b) std::swap(a, b);
    if(b == 0) return a;
    return gcd(b, a%b);
}

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

long long int Carmichael(long long int n, long long int prime=0, int pow_cnt=0) {
    if(prime == 2) {
        // n = 2^x
        if(pow_cnt == 1) return 1;
        if(pow_cnt == 2) return 2;
        return 1LL << (pow_cnt - 2);
    }
    else if(prime > 0) {
        // n = p^x (p is odd-prime number)
        return n / prime * (prime - 1);
    }
    else {
        long long int ans = 1;
        std::map<long long int, int> primes;
        for(long long int i=2; i*i<=n; i++) {
            while(n % i == 0) {
                primes[i]++;
                n /= i;
            }
        }
        if(n != 1) primes[n]++;

        for(auto x : primes) {
            long long int m = 1;
            for(int i=0; i<x.second; i++) m *= x.first;
            ans = lcm(ans, Carmichael(m, x.first, x.second));
        }
        return ans;
    }
}

// ?´???°??¨??????
std::vector<long long int> OutDivisor(long long int n) {
    std::vector<long long int> ret;
    for(long long int i=1; i*i<=n; i++) {
        if(n % i == 0) {
            ret.push_back(i);
            if(i*i!=n) ret.push_back(n / i);
        }
    }
    return ret;
}

long long int mod_pow(long long int x, long long int n, long long int MOD) {
    if(n == 0) return 1;
    long long int  res = mod_pow((x * x) % MOD, n / 2, MOD);
    if(n & 1) res = (res * x) % MOD;
    return res;
}

int main() {
    while(1) {
        long long int ans = 1;
        for(int i=0; i<3; i++) {
            long long int a, m; scanf("%lld%lld", &a, &m);
            if(a == 0) return 0;
            int C = Carmichael(m);
            std::vector<long long int> divisor = OutDivisor(C);
            
            long long int temp = INF;
            for(auto x : divisor) {
                long long int value = C / x;
                if(mod_pow(a, value, m) == 1) {
                    temp = std::min(temp, value);
                }
            }
            ans = lcm(ans, temp);
        }
        printf("%lld\n", ans);
    }
    return 0;
}