图片来源:https://wenku.baidu.com/view/d2414ffe04a1b0717fd5dda8.html
Create a code to determine the amount of integers, lying in the set [X; Y] and being a sum of exactly K different integer degrees of B.
Example. Let X=15, Y=20, K=2, B=2. By this example 3 numbers are the sum of exactly two integer degrees of number 2:
17 = 2 ^4+2 ^0,
18 = 2 ^4+2 ^1,
20 = 2 ^4+2^ 2.
#include<bits/stdc++.h>
using namespace std;
int digit[33];
typedef long long LL;
const int N = 50;
int f[N][N]; //f[i][j]表示前i个中选 j 个 1的个数
void init()
{
f[0][0] = 1;
for(int i=1;i<33;i++)
{
f[i][0] = f[i-1][0];
for(int j=1;j<=i;j++)
{
f[i][j] = f[i-1][j] + f[i-1][j-1];
}
}
}
int solve(int x,int k,int B)
{
int len=-1;
//vector<int> v;
while(x)
{
digit[++len]=x%B;
//v.push_back(x%B);
x/=B;
}
int cnt = 0,ans = 0;
for(int i=len;i>=0;i--)
{
if(digit[i]==1) // 如果为 1,则依次求解
{
ans+=f[i][k-cnt]; //need
cnt++;
if(cnt==k)
break;
}
else if(digit[i]>1) //假如大于1的话,相当于所有的位可以为 1,所以直接求解跳出
{
ans += f[i+1][k-cnt];
break;
}
}
if(cnt==k)
ans++;
return ans;
}
int main()
{
init();
int x,y,k,B;
while(~scanf("%d%d%d%d",&x,&y,&k,&B))
{
printf("%d\n",solve(y,k,B)-solve(x-1,k,B));
}
return 0;
}