import Data.Maybe
import Data.List
import Data.Ratio
import Debug.Trace

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
      | s > n = Nothing
      | otherwise = find (\b -> b > 1 && f b n == s) ([2..rt+1] ++ (map (\p -> div (n-s) p + 1) [rt,rt-1..1]))
      where
        rt = floor (sqrt $ fromIntegral n)