#include<iostream>
#include<string.h>
#include<vector>
#include<list>
#include<stdio.h>
#include<math.h>
#include<iomanip>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#define range(i,a,b) for(int i = (a); i < (b); i++)
#define rep(i,b) range(i,0,b)
#define debug(x) cout << "debug " << x << endl;
using namespace std;

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