let rec seq a b = if a >= b then [] else a :: seq (a+1) b

let sqrt_int x = int_of_float (sqrt (float_of_int x))

let rec sum_dig x b = if x <= 0 then 0 else x mod b + sum_dig (x/b) b

(*
 * `b >= sqrt(n)`
 * n = p*b + q, s = p + q
 * n = p*b + s - p
 * b = (n - s)/p + 1
 *)

let () =
  Scanf.scanf "%d %d" begin fun n s ->
    if n = s then n+1 else
    let b0 =
      seq 2 (sqrt_int n + 1) |> List.fold_left (fun v b ->
        match v with
        | Some _ -> v
        | None -> begin
          let s' = sum_dig n b in
          if s = s' then Some b else None
        end) None
    in
    match b0 with
    | Some b -> b
    | None -> begin
      seq 1 (sqrt_int n + 1) |> List.fold_left (fun v p ->
        if (n-s) mod p = 0 && sum_dig n ((n-s)/p + 1) = s then
          Some ((n-s)/p + 1)
        else
          v
      ) None
    end |> function None -> -1 | Some b -> b
  end |> Printf.printf "%d\n"