#include<iostream>
#include<vector>
#include<algorithm>

typedef long long ll;

using namespace std;

int gcd(ll a,ll b){
  if(b==0)return a;
  return gcd(b, a%b);
}

ll lcm(ll a,ll b){
  return (a*b)/gcd(a,b);
}

ll lcm_n(vector<ll> &num){
  int l=num[0];
  for(int i=1;i<num.size();i++)l=lcm(l,num[i]);
  return l;
}

int main(void){

  ll m[4],a[4];

  while(true){

    int b=0;
    for(int i=1;i<4;i++){
      cin >> a[i] >> m[i];
      b|=a[i]|m[i];
    }
    if(!b)break;
    
    ll cnt=0,x=1,y=1,z=1;
    vector<ll>num;
    num.clear();

    while(true){
      if(cnt!=0 && x==1)break;
      x=(a[1]*x)%m[1];
      cnt++;
    }
    num.push_back(cnt);
    cnt=0;

    while(true){
      if(cnt!=0 && y==1)break;
      y=(a[2]*y)%m[2];
      cnt++;
    }
    num.push_back(cnt);
    cnt=0;

    while(true){
      if(cnt!=0 && z==1)break;
      z=(a[3]*z)%m[3];
      cnt++;
    }
    num.push_back(cnt);

    cout << lcm_n(num)<< endl;
  }

  return 0;
}