#include<iostream>
using namespace std;
int main(){
long a1,m1,a2,m2,a3,m3,x,y,z,n;
while(cin>>a1){
cin>>m1>>a2>>m2>>a3>>m3;
if(a1==0)break;
x=y=z=1;n=1;
for(;;){
x=(a1*x)%m1;
y=(a2*y)%m2;
z=(a3*z)%m3;
if(x==1&&y==1&&z==1)break;
n++;
}
cout<<n<<endl;
}
return 0;
}