Problem:
Score : 500 points

Problem Statement

For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:

f(b,n) = n, when n < b

f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b

Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.

Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:

f(10,\,87654)=8+7+6+5+4=30

f(100,\,87654)=8+76+54=138

You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

Constraints

1 \leq n \leq 10^{11}

1 \leq s \leq 10^{11}

n,\,s are integers.

Input

The input is given from Standard Input in the following format:

n
s

Output

If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-1

Solution in Haskell (GHC 7.10.3) (judge verdict: Wrong Answer)

import Data.Maybe

main = do
  n <- readLn :: IO Int
  s <- readLn :: IO Int
  let rN = floor . sqrt . realToFrac $ n
      rN' = if rN^2 == n then rN - 1 else rN
      ans1 = filter (/=Nothing) $ map (solve n s) [2..rN]
  if n < s
    then print (-1)
    else if length ans1 > 0
           then print $ fromJust $ head ans1
           else let ans2 = map fromJust . filter (/=Nothing) $ map (solve' n s) [1..rN']
                in if length ans2 > 0 && n >= s
                     then print $ minimum ans2
                     else print (-1)

f :: Int -> Int -> Int
f b n
  | n < b = n
  | otherwise = (f b $ div n b) + mod n b

solve :: Int -> Int -> Int -> Maybe Int
solve n s b = let ans = f b n
              in if ans == s then Just b
                             else Nothing

solve' :: Int -> Int -> Int -> Maybe Int
solve' n s p = let b = (+1) $ div (n - s) p
               in if b == 1
                    then Nothing
                    else let ans = f b n
                         in if ans == s then Just b
                                        else Nothing