def gcd(m, n)
    if m < n 
        gcd(n, m)
    elsif n == 0
        m   
    else
        gcd(n, m % n)
    end 
end

loop do
    ns = gets.split.map(&:to_i)
    break if ns[0] == 0
    ks = ns.each_slice(2).map do |a, m|
        x = a 
        k = 1 
        until x == 1    
            k += 1
            x = x * a % m 
        end 
        k   
    end 
    p ks.inject(1){|lcm, x| x * lcm / gcd(x, lcm)}
end