D - Digit Sum Editorial /

Time Limit: 2 sec / Memory Limit: 256 MiB

配点 : 500500

問題文

22 以上の整数 bb および 11 以上の整数 nn に対し、関数 f(b,n)f(b,n) を次のように定義します。

  • n<bn < b のとき f(b,n)=nf(b,n) = n
  • nbn \geq b のとき f(b,n)=f(b,floor(n/b))+(n mod b)f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b)

ここで、floor(n/b){\rm floor}(n / b)n/bn / b を超えない最大の整数を、 n mod bn \ {\rm mod} \ bnnbb で割った余りを表します。

直感的に言えば、f(b,n)f(b,n) は、nnbb 進表記したときの各桁の和となります。 例えば、

  • f(10,87654)=8+7+6+5+4=30f(10,\,87654)=8+7+6+5+4=30
  • f(100,87654)=8+76+54=138f(100,\,87654)=8+76+54=138

などとなります。

整数 nnss が与えられます。 f(b,n)=sf(b,n)=s を満たすような 22 以上の整数 bb が存在するか判定してください。 さらに、そのような bb が存在するならば、その最小値を求めてください。

制約

  • 1n10111 \leq n \leq 10^{11}
  • 1s10111 \leq s \leq 10^{11}
  • n,sn,\,s はいずれも整数である

入力

入力は以下の形式で標準入力から与えられる。

nn
ss

出力

f(b,n)=sf(b,n)=s を満たす 22 以上の整数 bb が存在するならば、そのような bb の最小値を出力せよ。 そのような bb が存在しないならば、代わりに -1 を出力せよ。


入力例 1Copy

Copy
87654
30

出力例 1Copy

Copy
10

入力例 2Copy

Copy
87654
138

出力例 2Copy

Copy
100

入力例 3Copy

Copy
87654
45678

出力例 3Copy

Copy
-1

入力例 4Copy

Copy
31415926535
1

出力例 4Copy

Copy
31415926535

入力例 5Copy

Copy
1
31415926535

出力例 5Copy

Copy
-1

Score : 500500 points

Problem Statement

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

  • f(b,n)=nf(b,n) = n, when n<bn < b
  • f(b,n)=f(b,floor(n/b))+(n mod b)f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when nbn \geq b

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

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

  • f(10,87654)=8+7+6+5+4=30f(10,\,87654)=8+7+6+5+4=30
  • f(100,87654)=8+76+54=138f(100,\,87654)=8+76+54=138

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

Constraints

  • 1n10111 \leq n \leq 10^{11}
  • 1s10111 \leq s \leq 10^{11}
  • n,sn,\,s are integers.

Input

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

nn
ss

Output

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


Sample Input 1Copy

Copy
87654
30

Sample Output 1Copy

Copy
10

Sample Input 2Copy

Copy
87654
138

Sample Output 2Copy

Copy
100

Sample Input 3Copy

Copy
87654
45678

Sample Output 3Copy

Copy
-1

Sample Input 4Copy

Copy
31415926535
1

Sample Output 4Copy

Copy
31415926535

Sample Input 5Copy

Copy
1
31415926535

Sample Output 5Copy

Copy
-1


2025-06-08 (Sun)
00:46:33 +00:00