{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} import Control.Applicative import Control.Monad import Control.Arrow import Data.List import Data.Maybe import Data.Char import Text.Printf readInt = ( readLn :: IO Int ) getInts = map ( read :: String -> Int ) . words <$> getLine which a b f = if f then a else b mp [ a, b ] = ( a, b ) main = do [ p, q ] <- getInts print $ fromMaybe ( -1 ) $ solve p q solve p 1 = Just ( p - 1 ) solve p q | g /= 1 = solve ( p `div` g ) ( q `div` g ) | p < q = succ <$> solve q p | p == q = Nothing | otherwise = ( p `div` q + ) <$> solve ( p `mod` q ) q where g = gcd p q