#include <iostream>
#include <cstdio>
using namespace std;

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