#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <fstream>
#include <sstream>
#include <math.h>
#include <queue>
#include <stack>

using namespace std;


int a1, m1, a2, m2, a3, m3;

int main(){
    while(cin>>a1 >>m1 >>a2 >>m2 >>a3 >>m3){
        if(a1==0 && m1==0 && a2==0 && m2==0 && a3==0 && m3==0)break;
        
        long long int x,y,z,count;
        x=1;
        y=1;
        z=1;
        count=0;
        
        x=(a1*x)%m1;
        y=(a2*y)%m2;
        z=(a3*z)%m3;
        count++;
        
        while(!(x==1&&y==1&&z==1)){
            x=(a1*x)%m1;
            y=(a2*y)%m2;
            z=(a3*z)%m3;
            count++;
        }
        
        cout<<count<<endl;
    }
}