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

#define int  long long int

signed main() {
  while(1) {
    int a, m[3] = {};
    for(int i = 0; i < 3; i++) {
      cin >> a >> m[i];
      if(a != 0 || m[i] != 0) {
	int x = 1;
	int cnt = 0;
	do {
	  x = a*x%m[i];
	  cnt++;
	}
	while(x != 1);
	m[i] = cnt;
	if(i){
	  int l = max(m[i], m[i-1]), r = min(m[i], m[i-1]);
	  while(l % r != 0) {
	    int temp = r;
	    r = l % r;
	    l = temp;
	  }
	  m[i] = m[i-1]/r*m[i];
	}
      }
    }
    if(m[2]) cout << m[2] << endl;
    else break;
  }
  return 0;
}