-- AtCoder My Practice
-- author: Leonardone @ NEETSDKASU
 
-- 解説読後
-- http://arc060.contest.atcoder.jp/data/arc/060/editorial.pdf
-- s > n のときは -1 を入れないと TLEすることも 
 
import qualified Data.List as L
 
main = print . solve . map read . lines =<< getContents
 
f b n
    | n < b     = n
    | otherwise = let (dv, md) = divMod n b in md + f b dv
 
solve [n, s]
    | n == s    = n + 1
    | s >  n    = -1
    | otherwise = ans where
        en = maximum . takeWhile (\i -> i * i <= n) $ [1 .. ]
        ans = case L.find ((==) s . snd) . map (\i -> (i, f i n)) $ [2 .. en] of
            Just (i, _) -> i
            Nothing -> if en > 0 then ans' else -1 where
                ans' = case L.find ((==) s . snd) . map (\i -> (i, f i n)) $ bs of
                    Just (j, _) -> j
                    Nothing -> -1
                bs = map ((+) 1 . fst) . filter ((==) 0 . snd) . map (divMod (n - s)) $ [ en - k | k <- [0 .. en - 1]]
 