#include <iostream>
#include <vector>  

using namespace std;

int main() {
    int a, b, c;
    int l, m, n;
    int x = 1;
    int y = 1;
    int z = 1;

    while(cin>>a>>l>>b>>m>>c>>n, a||b||c||l||m||n) {
        int nx = ( a * x ) % l;
        int ny = ( b * y ) % m;
        int nz = ( c * z ) % n; 
        int cnt = 1;
        while(1) {
            if ( nx == 1 && ny == 1 && nz == 1) break;

            nx = ( a * nx ) % l;
            ny = ( b * ny ) % m;
            nz = ( c * nz ) % n; 
            cnt++;
        }
        cout<<cnt<<endl;
    }

    return 0;
}