#include <cstdio>
#include <iostream>

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

  while(scanf("%d %d %d %d %d %d",&a1,&m1,&a2,&m2,&a3,&m3),
	a1||a2||a3||m1||m2||m3) {
    int x, y, z;

    x = y = z = 1;
    x = (a1*x) % m1;
    y = (a2*y) % m2;
    z = (a3*z) % m3;
    
    int count;
    for (count=1; x!=1||y!=1||z!=1; count++) {
      x = (a1*x) % m1;
      y = (a2*y) % m2;
      z = (a3*z) % m3;
    }

    printf("%d\n", count); 
  }
}