#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include<cstdio>
#include<cmath>
#define pb(in,tmp) in.push_back(tmp)
#define loop(i,a,b) for(int i=a;i<b;i++)
#define rep(i,b) loop(i,0,b)
#define all(in) in.begin(),in.end()
using namespace std;
int main(){
int a,b,c,d,e,f;
while(cin>>a>>b>>c>>d>>e>>f,a||b||c||d||e||f){
long long int co=0;
int x=1,y=1,z=1;
do{
x=a*x%b;
y=c*y%d;
z=e*z%f;
co++;
}while(x-1||y-1||z-1);
cout<<co<<endl;
}
}