import Control.Monad
import Data.List
import Data.Maybe

main = sol <$> readLn <*> readLn >>= print

sol n s = fromMaybe (-1) $ find (\b -> s==f b n) [2..n]

f b n
  | n < b     = n
  | otherwise = n `mod` b + f b (n `div` b)
