#include <stdio.h>

int main(){
  int a1,m1,a2,m2,a3,m3,x,y,z;
  while (1){
    scanf("%d %d %d %d %d %d",&a1,&m1,&a2,&m2,&a3,&m3);
    if (a1==0 && a2==0 && a3==0 && m1==0 && m2==0 && m3==0) return 0;
    x=a1%m1;
    y=a2%m2;
    z=a3%m3;
    int cnt=1;
    while (!(x==1 && y==1 && z==1)){
      cnt++;
      x=(a1*x)%m1;
      y=(a2*y)%m2;
      z=(a3*z)%m3;
    }
    printf("%d\n",cnt);
  }
}