main :: IO ()
main = do
  ss <- getLine
  let s = map (read :: String -> Int) . words $  ss
  if s == [0,0,0,0,0,0]
    then return ()
    else do
      let ans = cicles s [1,1,1] 0
      putStrLn $ show ans
      main

cicles :: [Int] -> [Int] -> Int -> Int
cicles [a1,m1,a2,m2,a3,m3] [1,1,1] 0  = cicles [a1,m1,a2,m2,a3,m3]
                                               [a1 `mod` m1,a2 `mod` m2, a3 `mod` m3]
                                               1
cicles _ [1,1,1] count = count
cicles [a1,m1,a2,m2,a3,m3] [x,y,z] count = cicles [a1,m1,a2,m2,a3,m3]
                                                  [x*a1 `mod` m1,y*a2 `mod` m2,z*a3 `mod` m3]
                                                  (count + 1)