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.
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.
题意:胖兄和妹子有一块长度为n的金子,可以买到任何东西(除了爱情)。
现在他们嫌还是不够便利,就想把这块金子切成小块在每次买东西时直接拿出对应价值的金子而不用等待老板找零了。现在问你最少切成多少块能够达到目的。
解题思路:分成1,2,3,4...肯定不对的!(我第一反应就是这么想的)
应该想 n分成的这小块,能把1~n之间所有的小块都能凑出来。
如7:
按123分的话是 1 2 3 1
按1 2 4 8 16分的话是 1 2 4
所以三块就够了
如8:
按123分的话是 1 2 3 2
按1 2 4 6 8 分的话是 1 2 4 1
虽然也是四块= =
也就是说 从2^0开始,2^1,2^2,2^3......直到n分不动为止,剩余的单独作为一块。
可以打表,也可以直接使用log2(n)的一个函数。最后不要忘记+1
------------------------------------------------------------------
嗯...思考了下原理,为什么要这样分。
我们把每个数对应的二进制写出来:
0000 0
0001 1
0010 2
0011 3
0100 4
0101 5
0110 6
0111 7
1000 8
可以看到每个数都可以由 第一次在那一位出现1的那个数 凑出来
如5:
0101 5
找到第一个1所对应的第一次出现的那个数:
0100 4(填上第一个1)
再找到第二1所对应的第一次出现的那个数:
0001 1(填上第二个1)
即0101=0100+0001
5=4+1
所以按照这样分的话能把区间内的每一个整数都能凑出来(因为每一位需要填1的地方都有数可以填)
AC代码:
#include<stdio.h>
#include<math.h>
int main()
{
int t,tt=1,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
printf("Case %d: ",tt++);
printf("%d\n",int(log2(n)+1));
}
return 0;
}