Cutting Game
Fat brother and Maze are playing a kind of special (hentai) game with a piece of gold of length N where N is an integer. Although, Fat Brother and Maze can buy almost everything in this world (except love) with this gold, but they still think that is not convenient enough. Just like if they would like to buy the moon with M lengths of the gold, the man who sold the moon need to pay back Fat Brother and Maze N-M lengths of the gold, they hope that they could buy everything they can afford without any change. So they decide to cut this gold into pieces. Now Fat Brother and Maze would like to know the number of the pieces they need to cut in order to make them fulfill the requirement. The number of the gold pieces should be as small as possible. The length of each piece of the gold should be an integer after cutting.
Input
The first line of the data is an integer T (1 <= T <= 100), which is the number of the text cases.
Then T cases follow, each case contains an integer N (1 <= N <= 10^9) indicated the length of the gold.
For each case, output the case number first, and then output the number of the gold pieces they need to cut.
1 3Sample Output
Case 1: 2Hint
In the first case, the gold can be cut into 2 pieces with length 1 and 2 in order to buy everything they can afford without change.
要使x个数可以表示n内的任何数,通过二进制发现,每个数取二进制位上的1即可
所以有2^0 + 2 ^1 + ……+ 2^m = n
等比数列求和2^x - 1 = n,所以我们只需求x这个次数即可,x = log2(n+1)
code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
int q_pow(int a,int b){
int ans = 1;
while(b){
if(b & 1)
ans *= a;
b >>= 1;
a *= a;
}
return ans;
}
int main(){
int t,cas = 0;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
int x = log2(n+1);
if(q_pow(2,x)-1 != n) x++;
printf("Case %d: %d\n",++cas,x);
}
return 0;
}