#include <bits/stdc++.h>

using namespace std;

struct Fly {
    int p, a, m;
};

int main() {

    Fly fly[3];
    int cnt;

    while(1){

        for(int i = 0; i < 3; ++i) {
            cin >> fly[i].a >> fly[i].m;
            fly[i].p = 1;
        }

        if(!(fly[0].a | fly[1].a | fly[2].a | fly[0].m | fly[1].m | fly[2].m)) {            break;
        }

        cnt = 0;

        do {
            for(int i = 0; i < 3; ++i) {
                fly[i].p = fly[i].a * fly[i].p % fly[i].m;
            }
            cnt++;
        } while(fly[0].p != 1 || fly[1].p != 1 || fly[2].p != 1);

        cout << cnt << endl;

    }

}