#include<iostream>
using namespace std;

int main(){
  int a1,m1,a2,m2,a3,m3;

  while(1){
    cin >> a1 >> m1 >> a2 >> m2 >> a3 >> m3;
    if(!a1 && !m1 && !a2 && !m2 && !a3 && !m3)break;

    int x = 1,y = 1,z = 1;
    long long int ans = 0;
    do{
      ans++;
      x = (a1*x)%m1;
      y = (a2*y)%m2;
      z = (a3*z)%m3;
    }while(x!=1 || y!=1 || z!=1);

    cout << ans << endl;
  }
}