-- AtCoder My Practice
-- author: Leonardone @ NEETSDKASU

-- 解説読後
-- http://arc060.contest.atcoder.jp/data/arc/060/editorial.pdf



import qualified Data.Array as A
import qualified Data.Map as M
import qualified Data.List as L

main = print . solve . map read . lines =<< getContents

f b n = f' n 0 where
    f' x y
        | x < b     = x + y
        | otherwise = let (dv, md) = divMod x b in f' dv (md + y)

solve [n, s]
    | n == s    = n + 1
    | otherwise = ans where
        ans = case L.find ((==) s . snd) . map (\i -> (i, f i n)) . takeWhile (\i -> i * i <= n) $ [2 .. ] of
            Just (i, _) -> i
            Nothing -> ans'
        bs = reverse . map ((+) 1 . fst) . filter ((==) 0 . snd) . map (divMod (n - s)) . takeWhile (\i -> i * i <= n) $ [1 .. ]
        ans' = case L.find ((==) s . snd) . map (\i -> (i, f i n)) $ bs of
            Just (i, _) -> i
            Nothing -> -1
        
