1 #define Troy 10/11/2017
2
3 #include <bits/stdc++.h>
4
5 using namespace std;
6
7 typedef long long ll;
8
9 ll f[100][9*20*20],P;
10
11 int num,p[100];
12
13 inline ll dfs(int pos,int sum,bool limit){
14 if(pos==0) return sum;
15 if(!limit&&f[pos][sum]!=-1) return f[pos][sum];
16 int end=limit?p[pos]:P-1;
17 ll ret=0;
18 for(int i=0;i<=end;i++)
19 ret+=dfs(pos-1,sum+(pos-1)*i,limit&&i==end);
20 if(!limit) f[pos][sum]=ret;
21 return ret;
22 }
23
24 inline ll dfs(int pos,int up,int sum,bool limit){
25 if(sum<0) return 0;
26 if(pos==0) return sum;
27 if(!limit&&f[pos][sum]!=-1) return f[pos][sum];
28 int end=limit?p[pos]:P-1;
29 ll ret=0;
30 for(int i=0;i<=end;i++)
31 if(pos>=up) ret+=dfs(pos-1,up,sum+i,limit&&i==end);
32 else ret+=dfs(pos-1,up,sum-i,limit&&i==end);
33 return limit==0?f[pos][sum]=ret:ret;
34 }
35
36 inline ll calc(ll n){
37 num=0;
38 do{
39 p[++num]=n%P;
40 n/=P;
41 }while(n);
42 memset(f,-1,sizeof(f));
43 ll ret=dfs(num,0,true);
44 for(int i=2;i<=num;i++)
45 memset(f,-1,sizeof(f)),ret-=dfs(num,i,0,true);
46 return ret;
47 }
48
49 int main(){
50 ll a,b;
51 scanf("%lld%lld%lld",&a,&b,&P);
52 printf("%lld\n",calc(b)-calc(a-1));
53 }