Domain: Algorithms & Data Structures

You are given two positive integers **n** and **k**. For every integer **x** such that
1 <= x <= n, write the representation of **x** in base **k** (without leading zeros).

Each representation is a sequence of digits. Collect all n such digit-sequences and sort
them in **lexicographic order**: two sequences are compared digit by digit from left to
right (each digit compared by its integer value); at the first position where they differ,
the sequence with the smaller digit comes first; if one sequence is a proper prefix of
the other, the shorter one comes first.

After sorting, index the array from 1 to n (1-based indexing).

**Your task:** For each test case, compute how many integers i (1 <= i <= n) satisfy the
following condition: the base-k representation of i appears **exactly at position i** in
the sorted array.

**Additionally, describe the algorithm you use and explain why it runs efficiently for
the given constraints.**

---

### Input

5
7 2
10 3
100 10
1000000000000000000 10
1000000000000000000 2

---

The number 5 inside the `Input` represents the number of test cases.

### Notes

- The representation of 1 in any base is the single digit [1].
- The number 7 in base 3 is [2, 1].
- The number 81 in base 9 is [1, 0, 0].
- For the first test case (n=7, k=2), the base-2 representations sorted
  lexicographically are:
  [1], [1,0], [1,0,0], [1,0,1], [1,1], [1,1,0], [1,1,1]
  corresponding to decimal values 1, 2, 4, 5, 3, 6, 7.
  The values i where position equals i are: i=1 (value 1 at position 1),
  i=2 (value 2 at position 2), i=6 (value 6 at position 6),
  i=7 (value 7 at position 7). So the answer is 4.

---

### Output

For each test case, output a single integer on its own line: the count of values i such
that the base-k representation of i is located at position i in the lexicographically
sorted array.


Grading rubric:
criterion: The response outputs 4 as the answer for the first test case (n=7, k=2).
weight: 10
criterion: The response outputs 1 as the answer for the second test case (n=10, k=3).
weight: 10
criterion: The response outputs 11 as the answer for the third test case (n=100, k=10).
weight: 10
criterion: The response outputs 11 as the answer for the fourth test case (n=10^18, k=10).
weight: 15
criterion: The response outputs 2 as the answer for the fifth test case (n=10^18, k=2).
weight: 15
criterion: The response describes a method for computing the lexicographic rank of a number by counting how many valid numbers (at most n) are lexicographically smaller, using prefix-based or subtree-based counting.
weight: 15
criterion: The response explains why the fixed-point solutions within each group of same-length representations form a contiguous range (or equivalently, why binary search is applicable), by arguing that the difference between lexicographic rank and numeric rank is non-decreasing within such a group.
weight: 15
criterion: The response correctly states or demonstrates that the algorithm runs in polynomial-in-log-n time (e.g., O((log n)^2) or O((log n)^3)) per test case, making it feasible for n up to 10^18.
weight: 10

Answer:
PROBLEM ANALYSIS
================

We must count how many x in [1..n] satisfy: lexicographic_rank(x) = x,
where lexicographic_rank(x) is the 1-based position of x's base-k
representation in the sorted array of all representations from 1 to n.

KEY INSIGHT: TRIE MODEL
========================

Model all base-k representations as paths in a digit trie:
- Root has children for digits 1..k-1 (no leading zeros)
- Each internal node has children for digits 0..k-1
- A node is "active" if the number it represents is <= n

Two traversal orders correspond to two rankings:
- BFS (level-order): visits by increasing length, then by numeric value
  within equal length. This gives bfs_rank(x) = x for all x.
- DFS (pre-order, children in digit order 0..k-1): visits in
  lexicographic order. This gives dfs_rank(x) = lexicographic_rank(x).

Therefore we need: count of x where dfs_rank(x) = x.

COMPUTING dfs_rank(x)
=====================

Given x with base-k digits d_1 d_2 ... d_L:

dfs_rank(x) = 1 + (number of valid entries < x in lex order)

Algorithm:
  rank = 0, prefix = 0
  For each digit position i (0-indexed):
    For every digit c from start_digit to d_i - 1:
      rank += subtree_size(prefix * k + c, k, n)
    prefix = prefix * k + d_i
    If this is not the last digit and prefix <= n:
      rank += 1   (count the prefix itself as a valid number)
  Return rank + 1

where start_digit = 1 for the first position, 0 otherwise.

SUBTREE SIZE (prefix counting)
==============================

Count of numbers in [1..n] whose base-k representation starts with
a given prefix:

  def subtree_size(prefix, k, n):
      low, high, count = prefix, prefix + 1, 0
      while low <= n:
          count += min(n + 1, high) - low
          low *= k
          high *= k
      return count

For summing over consecutive digits c in [a, b), use:
  subtree_range_size(prefix*k + a, prefix*k + b, k, n)
which avoids iterating over each digit individually (critical for large k).

MONOTONICITY AND BINARY SEARCH
==============================

Define f(x) = dfs_rank(x) - x.

Within each "layer" (set of numbers with the same base-k representation
length L), f(x) is non-decreasing. Proof: for consecutive x, x+1 in the
same layer, bfs_rank increases by 1 while dfs_rank increases by >= 1.

Consequence: the set of solutions {x : f(x) = 0} within each layer
forms a contiguous (possibly empty) range. We can binary search for the
first and last x satisfying f(x) = 0 in each layer.

FULL ALGORITHM
==============

For each test case (n, k):
  answer = 0
  For each digit-length L = 1, 2, ...:
    Compute layer range [lo, hi] where lo = k^(L-1), hi = min(k^L - 1, n)
    (For L=1: lo=1, hi=min(k-1, n))
    If lo > n: break
    Binary search in [lo, hi] for first x with dfs_rank(x) >= x
    Binary search in [lo, hi] for last x with dfs_rank(x) <= x
    If valid range found: answer += last - first + 1
  Output answer

COMPLEXITY: O((log_k n)^2 * log(layer_size)) per test case.
  - Number of layers: O(log_k n)
  - Binary search per layer: O(log(layer_size))
  - dfs_rank: O(log_k n) with range subtree counting
This handles n, k up to 10^18 efficiently.

VERIFICATION
============

Working Python solution:

  def to_digits(x, k):
      digits = []
      while x > 0:
          digits.append(x % k)
          x //= k
      return digits[::-1]

  def count_range_subtrees(lo_pref, hi_pref, k, n):
      low, high, count = lo_pref, hi_pref, 0
      while low <= n:
          count += min(n + 1, high) - low
          low *= k
          high *= k
      return count

  def lex_rank(x, k, n):
      digits = to_digits(x, k)
      rank, prefix = 0, 0
      for i, d in enumerate(digits):
          start = 1 if i == 0 else 0
          if d > start:
              rank += count_range_subtrees(prefix*k + start, prefix*k + d, k, n)
          prefix = prefix * k + d
          if i < len(digits) - 1 and prefix <= n:
              rank += 1
      return rank + 1

  def solve(n, k):
      count, L = 0, 1
      while True:
          if L == 1:
              lo, hi = 1, min(k - 1, n)
          else:
              lo = k ** (L - 1)
              if lo > n: break
              hi = min(lo * k - 1, n)
          if lo > hi:
              L += 1; continue
          a, b = lo, hi; first = hi + 1
          while a <= b:
              mid = (a + b) // 2
              if lex_rank(mid, k, n) >= mid: first, b = mid, mid - 1
              else: a = mid + 1
          a, b = lo, hi; last = lo - 1
          while a <= b:
              mid = (a + b) // 2
              if lex_rank(mid, k, n) <= mid: last, a = mid, mid + 1
              else: b = mid - 1
          if first <= last: count += last - first + 1
          L += 1
      return count

Verified against brute force for hundreds of random (n, k) pairs with
n up to 500 and k up to 30.

ANSWERS
=======

Test case 1: n=7, k=2           =>  4
Test case 2: n=10, k=3          =>  1
Test case 3: n=100, k=10        =>  11
Test case 4: n=10^18, k=10      =>  11
Test case 5: n=10^18, k=2       =>  2

Output:
4
1
11
11
2
```