#include <bits/stdc++.h>
using namespace std;
int a1, m1, a2, m2, a3, m3;
int x = 1, y = 1, z = 1;

void fd() {
    x = a1*x % m1;
    y = a2*y % m2;
    z = a3*z % m3;
}

void solve() {
    int cnt = 0;
    while(true) {
        fd();
        cnt++;
        if(x == 1 && (y == 1 && z == 1)){printf("%d\n", cnt); return;}
    }
}

int main(void) {
    while(cin >> a1 >> m1 >> a2 >> m2 >> a3 >> m3, ((a1|m1) | (a2|m2)) | (a3|m3)) {
        solve();
    }
    return(0);
}