import Control.Applicative
import Control.Monad.State

main = do
    list@[a1,m1,a2,m2,a3,m3] <- map read.words<$>getLine
    if all (== 0) list then return ()
                       else do
                           print $ searchMinCycle [a1,m1] [a2,m2] [a3,m3]
                           main

nextP :: Int -> Int -> Int -> Int
nextP a m x = a*x `mod` m

searchMinCycleP :: [Int] -> Int
searchMinCycleP [a,m] = evalState (loop next 1) 0
    where next = nextP a m

searchMinCycle :: [Int] -> [Int] -> [Int] -> Int
searchMinCycle parX parY parZ= foldl1 lcm [xLoop, yLoop, zLoop]
    where xLoop = searchMinCycleP parX
          yLoop = searchMinCycleP parY
          zLoop = searchMinCycleP parZ

loop :: (Int -> Int) -> Int -> State Int Int
loop f p = do
    let p' = f p
    if p' == 1 then (+1)<$>get
               else modify (+1) >> loop f p'

