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

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

sol n s
  | n == s    = n+1
  | n == 1    = -1
  | otherwise = bool step1 step2 $ step1 == -1
  where
  step1 = fromMaybe (-1) $ find ((s==) . (flip f n)) [2..n']
  n' = floor . sqrt $ fromIntegral n
  step2 = fromMaybe (-1) $ find ((s==) . (flip f n) . h) [1..n']
  h p = (n-s) `div` p + 1

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