https://codeforces.com/gym/101972/problem/J
J. Even Numbers
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
inputCopy
2
1
2
outputCopy
0
1
打表
#include <algorithm>
#include <cstdio>
#include <iostream>
using namespace std;
int a[100][100];
int main() {
int n = 32;
for (int i = 0; i < n; i++) a[0][i] = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j > i) a[i][j] = 0;
if (i == j) a[i][j] = 1;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j < i) a[i][j] = (a[i - 1][j - 1] + a[i - 1][j]) % 2;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (a[i][j] == 1)
printf("*");
else
printf(" ");
}
printf("\n");
}
}
n到10的18次方,这么大的数据范围,最多也就是log(n)的算法,或者说是有规律。通过打表发现,对应的2的幂次恰好是 i 的二进制表示中 1 的个数( i 代表第 i 行)
代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
long long n, tn, tmp = 0;
cin>>n;
tn = n;
while(tn){
tn -= tn & (-tn);
tmp++;
}
cout<<n + 1 - (1ll << tmp)<<endl;
}
}