#include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 2;
const long long MOD = 1e9 + 7;
const long long INF = 1e16;
const long long LOG = 25;
long long binpow(long long a, long long b, long long m) {
  a %= m;
  long long res = 1;
  while (b > 0) {
    if (b & 1) res = res * a % m;
    a = a * a % m;
    b >>= 1;
  }
  return res;
}
long long func(long long b, long long n) {
  if (b < 2) return 0;
  long long sum = 0;
  while (n) {
    sum += (n % b);
    n /= b;
  }
  return sum;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  long long n, second;
  cin >> n >> second;
  if (n == second) {
    cout << n + 1 << "\n";
    return 0;
  }
  long long ans = INF;
  for (long long x = 1; x <= sqrt(n); x++) {
    if (func(x, n) == second) {
      ans = min(ans, x);
    }
  }
  if (func(n, n) == second) {
    ans = min(ans, n);
  }
  if (func(n - second, n) == second) {
    ans = min(ans, n - second);
  }
  long long lol = n - second;
  for (long long x = 1; x <= sqrt(lol); x++) {
    if (lol % x == 0) {
      long long y = lol / x;
      x++, y++;
      if (func(x, n) == second) {
        ans = min(ans, x);
      }
      if (func(y, n) == second) ans = min(ans, y);
      x--;
    }
  }
  if (ans == INF) ans = -1;
  cout << ans << "\n";
  return 0;
}
