C++#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n,d,k,x,ans=0;
cin>>n>>d>>k>>x;
for(int i=n;i<n+d;i++){
int s=i;
while(s){
if(s%k==x){
ans++;
}
s/=k;
}
}
cout<<ans<<endl;
}
/*
这出的什么78题
小可爱出题者
SB SB SB SB SB SB SB SB SB SB SB SB S
.####...#####..########......#......#
#.......#...#......#........##.....##
#.......#...#......#.......#.#....#.#
.###....#####......#......#..#...#..#
....#...#....#.....#.....#...#..#...#
....#...#... #.....#....#....#.#....#
####....#####......#...#.....#......#
SB SB SB SB SB SB SB SB SB SB SB SB S
*/
return 0;
}