Even Numbers
Description
Yousef loves playing with functions in his free time. Today, he invents the following function:
Yousef will give you a list of queries, and you need to find the answers for them. For each query, you are given an integer n, and your task is to count the number of integers m in which (0 ≤ m ≤ n) and calc(n, m) is an even number. Can you?
Input
The first line contains an integer T (1 ≤ T ≤ 105) specifying the number of test cases.
Each test case consists of a single line containing an integer n (0 ≤ n ≤ 1018), as described in the problem statement above.
Output
For each test case, print a single line containing the number of integers m in which (0 ≤ m ≤ n) and calc(n, m) is an even number.
Example
input
2
1
2
output
0
1
题目分析
题意:有一个函数cal(n,m),求有多少个m使得cal(n,m)为偶数,其中(0 <= m <= n)
思路:先打了个表发现 cal(n,m) 即为组合数C ,因此,我们只需要知道 C
,C
,C
....C
中一共有多少个偶数,不过n的值可以高达1e18,肯定不能直接算,不过这里有一个神奇的方法,对于组合数C
,如果 a & b == b ,那么C
为奇数,而我们知道,只要a在二进制下,值为0的位置,b在二进制下也是0,那么 a& b == 0,为此,当我们知道了a在二进制下1的个数x,那么满足这个条件的b就有 2^x 个了,因此令C
为偶数时b的取值有 a + 1 - 2 ^x 种
总结:先预处理出 2 ^ x ( 0 <= x <=63),求输入n的在二进制下有多少个1,记数量为x,那么结果就是 n +1 - 2 ^x
代码区
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<string>
#include<fstream>
#include<vector>
#include<stack>
#include <map>
#include <iomanip>
#include <random>
#define bug cout << "**********" << endl
#define show(x,y) "["<<x<<","<<y<<"]"
//#define LOCAL = 1;
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll mod = 1e6 + 3;
const int Max = 5e2 + 10;
ll t, n, m, k;
ll a[100];
int main()
{
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
a[0] = 1;
for (int i = 1;i <= 63;i++)
{
a[i] = (a[i - 1] << 1);
}
scanf("%lld", &t);
while (t--)
{
scanf("%lld", &n);
k = n;
m = 0;
while (k)
{
if (k & 1) m++;
k >>= 1;
}
printf("%lld\n", n + 1 - a[m]);
}
return 0;
}