Http://acm.zju.edu.cn/onlinejudge/showProblem.do? Problemid = 3179
Example:
Give you two numbers a B, such as 3 5
3-> the binary number of 5 is 11 100 101 110.
Returns the probability of occurrence of each number.
In the preceding example, P = 1/4*(1 + 1/3 + 2/3 + 2/3)
Method: preprocessing a DP [I] [2]: DP [I] [1] indicates the sum of 1 in the binary number with the highest bit as 1 and the length as I
DP [I] [0] indicates the sum of 1 in the binary number where the highest bit is 0 and the length is I.
This question has a special place in Statistics. Binary numbers of the same length must be processed together.
Then you can take a closer look at the boundary.
#include<stdio.h>#include<string.h>double dp[30][2];double d[30][2];void init(){memset(dp,0,sizeof(dp));memset(d,0,sizeof(d));for(int i=1;i<30;i++){ dp[i][1]=dp[i-1][1]+dp[i-1][0]+(1<<(i-1));dp[i][0]=dp[i-1][1]+dp[i-1][0];}}double CC(int num){double sum=0;int cnt=0;for(int i=29;i>=0;i--){if(num&(1<<i)){sum+=dp[i+1][0];sum+=(double)(1<<i)*cnt;cnt++;}}sum+=cnt;return sum;}double calc(int a,int b){double cnt=b-a+1;double sum=0;int f1,f2;for(int i=29;i>=0;i--){if(a&(1<<i)){f1=i;break;}}for(int i=29;i>=0;i--){if(b&(1<<i)){f2=i;break;}}for(int i=f1+2;i<=f2;i++)sum+=dp[i][1]/i;if(f2-f1==0){double num=CC(b)-CC(a-1);sum=num/(f1+1);}else {int p=(1<<(f1+1))-1;double num=CC(p)-CC(a-1);sum+=num/(f1+1);p=(1<<f2);num=CC(b)-CC(p-1);sum+=num/(f2+1);}return sum/cnt;}int main(){int t,a,b;init();scanf("%d",&t);while(t--){scanf("%d%d",&a,&b);printf("%lf\n",calc(a,b));}return 0;}