#include <iostream>
#include <complex>
#include <sstream>
#include <string>
#include <algorithm>
#include <deque>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <vector>
#include <set>
#include <limits>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;
#define REP(i, j) for(int i = 0; i < (int)(j); ++i)
#define FOR(i, j, k) for(int i = (int)(j); i < (int)(k); ++i)
#define SORT(v) sort((v).begin(), (v).end())
#define REVERSE(v) reverse((v).begin(), (v).end())
typedef complex<double> P;
const int N = 3;

int A[N], M[N];

int solve(int x, int y, int z, int cnt){
  if(x == 1 && y == 1 && z == 1) return cnt;
  return solve((A[0] * x) % M[0], (A[1] * y) % M[1], (A[2] * z) % M[2], cnt + 1);
}

int main() {
  while(true){
    REP(i, N) cin >>A[i] >>M[i];
    if(A[0] == 0) break;
    cout <<solve(A[0] % M[0], A[1] % M[1], A[2] % M[2], 1) <<endl;
  }
  return 0;
}