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

main = sol <$> readLn <*> readLn >>= print . fromMaybe (-1)

sol n s
  | n == s    = Just (n+1)
  | n < s     = Nothing
  | otherwise = find (liftM2 (&&) (>1) ((s==) . flip f n)) $
  	  [2..n'+1] ++ fmap (\p -> (n-s) `div` p + 1) [n',n'-1..1]
  where
  n' = floor . sqrt $ fromIntegral n

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