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

int a[3], m[3];

void solve() {
  int x = 1, y = 1, z = 1;
  for(int i = 1; ; ++i) {
    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) {
      cout << i << endl;
      return;
    }
  }
}

main() {
  while(1) {
    bool allzero = true;
    for(int i = 0; i < 3; ++i) {
      cin >> a[i] >> m[i];
      if(a[i] || m[i]) allzero = false;
    }
    if(allzero) break;
    solve();
  }
}