import Control.Applicative ((<$>), (<*>))
import Control.Monad
import Data.List

main :: IO ()
main = do
  solve <$> getl toIex <*> getl toIex >>= print

solve :: Integer -> Integer -> Integer
solve n s
  | null ls = -1
  | otherwise = head ls
  where
    ls =  filter (\b -> f n b == s) [2..n+1]
    f x b
      | x < b = x
      | otherwise = f (x `div` b) b + x `mod` b

toIex :: String -> Integer
toIex = read

toDbl :: String -> Double
toDbl = read

wrds :: (String -> a) -> String -> [a]
wrds f = map f . words

getl :: (String -> a) -> IO a
getl f = f <$> getLine
