import Data.Maybe
import Data.List

main = do
  n <- readLn :: IO Integer
  s <- readLn :: IO Integer

  print $ case solve n s of
    Just x -> x
    Nothing -> -1

  where
    f b n
      | n < b = n
      | n >= n = (mod n b) + f b (div n b)

    maybeSeq xs = if c==[] then Nothing else Just c
      where c = catMaybes xs
      
    solve :: Integer -> Integer -> Maybe Integer
    solve n s
      | s == n = Just $ n+1
      | otherwise = fmap minimum $ maybeSeq [f1, f2]

      where
        rt = floor (sqrt $ fromIntegral n)
        f1 = let l = filter (\b -> f b n == s) [2..rt] in if l == [] then Nothing else Just $ minimum l
        f2 = fmap maximum $ maybeSeq $ map (\b -> solve' (n - (div n b) * b + (div n b)) s b) (reverse [2..rt])
        
        solve' x s b
           | s > x = Nothing
           | otherwise = if mod (x-s) (b-1) == 0 && div (x-s) (b-1) < (div n (b-1) - div n b) then
                           Just $ n - div n b + div (x-s) (b-1)
                         else
                           Nothing
