Problem Statement
For integers b(_b_≥2) and n(_n_≥1), let the function f(b,n) be defined as follows:
- f(b,n)=n, when n<b
- f(b,n)=f(b, floor(n_⁄_b))+(n mod b), when n_≥_b
Here, floor(n_⁄_b) denotes the largest integer not exceeding n_⁄_b, and n 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_≥2) such that f(b,n)=s. If the answer is positive, also find the smallest such b.
Constraints
- 1≤_n_≤1011
- 1≤_s_≤1011
- 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_≥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
题意
给定一个(n)和一个(s),找到一个最小的(b)使得(n)在(b)进制下各位之和为(s).
分析
假设(n)表示为(b)进制之后各位上的数字从低位到高位分别为(a_0,a_1,a_2,...),显然我们可以得到如下两个等式
并且对于(forall i in [0,+infty])都有(a_i<b igwedge a_i>=0);
- 当(1)式中的最高次幂至少二次时,(bleq sqrt{n}),所以我们可以枚举(b)的值从(2)到(sqrt n),每次求出(b)进制下各位数字之和看是否等于(s)
- 当(1)式中的最高次幂为1次时,有$$
left{
egin{aligned}
a_0+a_1b=n
a_0+a_1=s
end{aligned}
ight.