import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0; 
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
    long n = scan!long;
    long s = scan!long;

    long infty = n + 999;
    long ans = infty;
    for(long b = 2; b * b <= n; b ++) if(digsum(n, b) == s) ans.lowerTo(b), log("ans:", ans);

    long[] ds = (n - s).divisors;
    foreach(d; ds) if(digsum(n, d + 1) == s) ans.lowerTo(d + 1), log("ans:", ans);

    if(n == s) ans.lowerTo(n + 1);

    if(ans >= infty) "-1".writeln;
    else ans.writeln;
}

long digsum(long n, long b){
    long ans;
    log("n:", n, "b:", b);
    while(n > 0){
        ans += n % b;
        n /= b;
    }
    log("sum:", ans);
    return ans;
}

/// 約数の集合
/// 1とその数自身も含む、正の約数の集合。
/// 例 divisors(48) = [1, 2, 3, 4, 6, 8, 12, 16, 24, 48]
/// O(√N)
long[] divisors(long a){
	long[] res, res2;
	for(long d = 1; d * d <= a; d ++){
		if(a % d == 0) res ~= d, res2 ~=  a / d;
	}
	foreach_reverse(d; res2) if(res[$ - 1] < d) res ~= d;
	return res;
}
