#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <vector>
using namespace std;
typedef long long ll;
const ll N = 33;
const ll mod = 1000000007;
ll ans = 0;
ll K, B;
ll dp[N][N];
ll C[N][N];
void init() {
for (int i = 0; i < N; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0)
C[i][j] = 1;
else
C[i][j] = C[i - 1][j] + C[i - 1][j - 1];
}
}
}
ll DP(ll n) {
if (n == 0) return 0;
vector<int> nums;
ll now = n;
while (now) {
nums.push_back(now % B);
now /= B;
}
ll res = 0, last = 0;
for (int i = nums.size() - 1; i >= 0; i--) {
if (nums[i] > 0) {
res += C[i][K - last];
if (nums[i] > 1) {
if (K - last - 1 >= 0) res += C[i][K - last - 1];
break;
} else {
last++;
if (last > K) break;
}
}
if (!i && last == K) res++;
}
return res;
}
void solve() {
ll a, b;
cin >> a >> b >> K >> B;
cout << DP(b) - DP(a - 1) << endl;
}
signed main() {
ios::sync_with_stdio(0);
ll t = 1;
init();
while (t--) solve();
return 0;
}