루미 알고리즘

#1626실버The Calculator

PO 2025 학교 예선코딩출제 Joshua Andersson영어 원문이 문제가 어렵다면 — 배우는 순서 보기

영어 원문입니다. 원문의 수식·표를 글자로 옮겨 모양이 다를 수 있습니다. 정확한 내용은 원문 페이지에서 확인하세요. 원문 페이지 열기 (새 창)

Problem

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 ≤ k ≤ 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 ≤ N ≤ 10^9), the value of the kålnami code.

The next line contains the digit M (2 ≤ M ≤ 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.

GroupPointsConstraints
120M=3, N ≤ 10.
220M=2
320N ≤ 10^5
440No 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. × 2
  3. × 2

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

  1. +1
  2. × 3
  3. × 3
  4. +2
  5. × 3

예제

예제 1

입력
4
2
출력
3

예제 2

입력
33
3
출력
5

출처 표기

출처: Programmeringsolympiaden 2025년 학교 예선 · 원문 페이지 · 이용 조건 CC BY-SA · LaTeX 원문을 화면용 글로 옮겼습니다(수식·표의 모양이 다를 수 있습니다). 내용은 고치지 않았습니다.

크리에이티브 커먼즈 저작자표시-동일조건변경허락.

문제 출처: 한국정보올림피아드(KOI) (CC BY-NC-SA 4.0) · International Olympiad in Informatics (IOI) (CC BY) · Centre for Education in Mathematics and Computing (CEMC), University of Waterloo (CC BY-NC 4.0) · Programmeringsolympiaden (CC BY-SA) · CSES Problem Set (Antti Laaksonen) (CC BY-NC-SA 4.0). 루미 알고리즘은 위 단체들과 관계없는 별도의 서비스이며, 자료는 원문 그대로 싣습니다. 문제마다 출처와 이용 조건을 따로 표기합니다.