Under construction

Still being built. Things may change

Diagnostic 0 : 1

Interview

Time limit2sMemory limit1024 MB

Summary
Count integers k in [a, b] whose base-m digit sum equals n, for up to 50,000 test cases.
Level

Medium5 of 10

Topics
Dynamic programming, Math
Solved
No attempts yet

Problem

For each positive integer mm with 2≤m2 \le m, define the function fmf_{m} on the set of non-negative integers as follows.

fm(x)={0(x=0)fm(xm)(x≡0(modm))fm(⌊xm⌋)+1(x≢0(modm))f_{m}(x) = \begin{cases} 0 & (x = 0) \\ f_{m}\left(\dfrac{x}{m}\right) & (x \equiv 0 \pmod {m}) \\ f_{m}\left(\left\lfloor\dfrac{x}{m}\right\rfloor\right) + 1 & (x \not\equiv 0 \pmod {m}) \end{cases}

Given positive integers aa, bb, mm, and nn, find the number of integers kk with a≤k≤ba \le k \le b that satisfy fm(k)=nf_{m}(k) = n.

Input

The first line contains the number of test cases TT. (1≤T≤50 000)(1 \le T \le 50\,000)

Each of the next TT lines contains positive integers aa, bb, mm, and nn, separated by spaces. (1≤a≤b≤1018;(1 \le a \le b \le 10^{18}; 2≤m≤10;2 \le m \le 10; 1≤n≤100)1 \le n \le 100)

Output

For each test case, print on its own line the number of integers kk with a≤k≤ba \le k \le b that satisfy fm(k)=nf_{m}(k) = n, using the given aa, bb, mm, and nn.

Examples1

  1. Example 1

    Input
    3
    1 7 2 2
    8 12 3 1
    7 17 4 2
    
    Expected output
    3
    1
    8