#include <cstdio>

using namespace std;

int gcd(int a, int b){
  return b ? gcd(b, a % b) : a;
}

int main(){
  int a[3], b[3];
  while( ~scanf("%d %d %d %d %d %d", &a[0], &b[0], &a[1], &b[1], &a[2], &b[2]) && a[0]){
    unsigned int x[] = {1, 1, 1};
    unsigned int cnt[3] = {};
    unsigned int now = 0;
    while( !cnt[0] || !cnt[1] || !cnt[2] ){
      now++;
      for(int i = 0; i < 3; i++){
        x[i] = (a[i] * x[i]) % b[i];
        if(x[i] == 1 && !cnt[i]){
          cnt[i] = now;
        }
      }
    }
    cnt[0] = (cnt[0] * cnt[1]) / gcd(cnt[0], cnt[1]);
    printf("%u\n", (unsigned int)(cnt[0] * cnt[2]) / gcd(cnt[0], cnt[2]));
  }
  return 0;
}