#include<iostream>

using namespace std;

int main(){

  int a[3],m[3];
  while(cin >> a[0] >> m[0] >> a[1] >> m[1] >> a[2] >> m[2] && a[0]+a[1]+a[2]+m[0]+m[1]+m[2]){
    int x,y,z;
    x = y = z = 1;
    int rev = 0;
    while(1){
      rev++;
      x = a[0]*x%m[0];
      y = a[1]*y%m[1];
      z = a[2]*z%m[2];
      if(x == 1 && y == 1 && z == 1) break;
    }
    cout << rev << endl;
  }
  return 0;
}