import std.stdio;
import std.algorithm;
import std.string;
import std.functional;
import std.array;
import std.conv;
import std.math;
import std.typecons;
import std.regex;
import std.range;

void main(){

    while(true){
	int x,y,z;
	int x1,y1,z1;
	int l,m,n;
	auto s = readln().split().to!(int[]);
	if(s[0] == 0 && s[1] == 0 && s[2] == 0 && s[3] == 0 && s[4] == 0 && s[5] == 0 ) break;
	x1 = s[0];
	l = s[1];
	y1 = s[2];
	m = s[3];
	z1 = s[4];
	n = s[5];
	x = x1 % l;
	y = y1 % m;
	z = z1 % n;
	int ans = 1;
	while(!(x == 1 && y == 1 && z == 1)){
	    x = (x1 * x) % l;
	    y = (y1 * y) % m;
	    z = (z1 * z) % n;
	    ans++;
	}
	writeln(ans);
    }
}