#include <iostream>

using namespace std;

int main()
{
    int a[3], m[3];

    while (true) {
        int sum = 0;
        for (int i = 0; i < 3; i++) {
            cin >> a[i] >> m[i];
            sum += (a[i] + m[i]);
        }
        if (sum == 0)
            break;

        int x[3] = {1, 1, 1}, cnt = 0;

        while (true) {
            for (int i = 0; i < 3; i++)
                x[i] = (x[i] * a[i]) % m[i];

            cnt++;

            if (x[0] == 1 && x[1] == 1 && x[2] == 1)
                break;
        }
        cout << cnt << endl;
    }

    return 0;
}