-- Try AtCoder
-- author: Leonardone @ NEETSDKASU

import Data.List (find)

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

solve [1, _] = -1
solve [s, 1] = s
solve [n, s] = ans where
    f b n
        | n < b     = n
        | otherwise = let (d, m) = divMod n b in (f b d) + m
    ans = case find ((==) s . snd) $ map (\i -> (i, f i n)) [2 .. ] of
        Just (x, _) -> x
        Nothing -> -1
