import Control.Applicative

f b n
  | n < b = n
  | otherwise = f b n' + m
    where (n',m) = n `divMod` b

main = do
  n <- read <$> getLine :: IO Int
  s <- read <$> getLine :: IO Int
  let bs = filter ((==s).fst) [(f b n,b)|b<-[2,3..n]]
  print $ if null bs then -1 else snd(head bs)
