 #include<iostream>
 #include<stdio.h>
 #include<string>
 #include<math.h>
 #include<iomanip>
 #include<algorithm>
 #include<string.h>
 #include<cctype>
 #include<map>
 #include<set>
 #include<vector>
 #include<sstream>
 #include<stack>
 #include<queue>
 
 using namespace std;
 
 int main()
 {
   int a1,m1,a2,m2,a3,m3;
   while(cin>>a1>>m1>>a2>>m2>>a3>>m3)
   {
     int step;
     if(a1==0&&a2==0&&a3==0&&m1==0&&m2==0&&m3==0) break;
     else
     {
       int x=1;
       int y=1;
       int z=1;
       step=0;
       do
       {
         x=(a1*x)%m1;
         y=(a2*y)%m2;
         z=(a3*z)%m3;
         step++;    
       }while(!(x==1&&y==1&&z==1));     
     }                         
     cout<<step<<endl;         
   }
   //while(1);
   return 0;
 }