#include <iostream>
#include <string>
using namespace std; int f[][];
void init(){
f[][] =;
for(int i=;i<=;i++){
f[i][] = f[i-][];
for(int j=;j<=i;j++)
f[i][j] = f[i-][j]+f[i-][j-];
}
} int change(int x,int b){
string s;
while(x){
s = (char)(x%b+'')+s;
x = x/b;
}
for(int i=;i<s.size();i++)
if(s[i]>''){
for(int j=i;j<s.size();j++)
s[j] = '';
break;
}
x =;
for(int i=;i<s.size();i++){
x = x|((s[s.size()--i]-'')<<i);
}
return x;
} int cal(int x,int k){
int tot =,ans =;
for(int i=;i>;i--){
if(x&(<<i)){
tot++;
if(tot>k) break;
x = x^(<<i);
}
if((<<(i-))<=x){
ans += f[i-][k-tot];
}
}
if(tot + x==k) ans++;
return ans;
} int main()
{
init();
int x,y;
int k,b;
cin>>x>>y>>k>>b;
x= change(x,b);
y = change(y,b);
int resx = cal(x-,k);
int resy = cal(y,k);
cout<<resy-resx<<endl;
return ;
}