Hide

Problem G
The Calculator

Languages en sv

Rumors are circulating that your school-provided calculator can be upgraded using a secret code. You’ve heard that if you can get the calculator to display the secret kålnami code on its screen and then press the equals sign, the calculator will unlock several secret mathematical functions.

Your friend has figured out what the kålnami code is, but they tell you that you can’t input the code into the calculator in just any way. Initially, the calculator displays $0$. You can then perform the following operations:

  • Multiply the number displayed by $M$.

  • Add any number $k$ to the displayed number, where $k$ satisfies $0 \leq k \leq M-1$.

Fortunately, your friend has also discovered the value of $M$. This complicated process will only work if you perform as few operations as possible. Therefore, you want to determine the minimum number of operations required, given the kålnami code and the value of $M$.

Input

The first line of input contains the integer $N$ ($1 \leq N \leq 10^9$), the value of the kålnami code.

The next line contains the digit $M$ ($2 \leq M \leq 9$), whose meaning is described above.

Output

Print a single integer: the minimum number of operations required to make the calculator display the kålnami code $N$.

Scoring

Your solution will be tested on a set of test groups, each worth a number of points. Each test group contains a set of test cases. To get the points for a test group you need to solve all test cases in the test group.

Group

Points

Constraints

$1$

$20$

$M=3, N \leq 10$.

$2$

$20$

$M=2$

$3$

$20$

$N \leq 10^5$

$4$

$40$

No additional constraints.

Explanation of Samples

In sample 1, one way to input the code with the minimum number of operations is as follows:

  1. $+1$

  2. $\times 2$

  3. $\times 2$

In sample 2, an optimal solution is to perform the following operations:

  1. $+1$

  2. $\times 3$

  3. $\times 3$

  4. $+2$

  5. $\times 3$

Sample Input 1 Sample Output 1
4
2
3
Sample Input 2 Sample Output 2
33
3
5

Please log in to submit a solution to this problem

Log in