#P9002. [RC-07] 心跳

[RC-07] 心跳

Problem Description

For a positive integer xx, let f(x,B)f(x,B) denote the sum of digits of xx in base BB. We say a positive integer pp is BB-good if and only if for every positive integer q<pq<p, we have f(p,B)f(q,B)f(p,B)\ge f(q,B).

Given positive integers nn and BB, compute how many positive integers n\le n are BB-good.

Input Format

This problem contains multiple test cases in a single test file.

The first line contains the number of test cases TT.

The next TT lines each contain two positive integers n,Bn,B.

Output Format

Output TT lines. Each line contains one non-negative integer, the answer.

6
4 2
9 3
1000 2
1000 20
28238934 154154154154154
23389348458425 5
3
6
49
60
28238934
760

Hint

Sample Explanation

Here we only explain the output of the second query. In base 33, the digit sums of 1,2,3,4,5,6,7,8,91,2,3,4,5,6,7,8,9 are 1,2,1,2,3,2,3,4,11,2,1,2,3,2,3,4,1, respectively. From this, it is easy to see that only 1,2,4,5,7,81,2,4,5,7,8 are 33-good, so the output is 66.

Constraints

All testdata satisfy: 1T1051\le T\le 10^5, 1n10181\le n\le 10^{18}, 2B10182\le B\le 10^{18}.

  • Subtask 11 (5050 points): T104T\le 10^4, n,B100n,B\le 100.
  • Subtask 22 (3030 points): B=2B=2.
  • Subtask 33 (2020 points): no special constraints.

Translated by ChatGPT 5