CF--A. Tricky Sum


A. Tricky Sum
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.

For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 =  - 4, because 1, 2 and 4 are20,21 and22 respectively.

Calculate the answer for t values of n.

Input

The first line of the input contains a single integer t (1 ≤ t ≤ 100) — the number of values ofn to be processed.

Each of next t lines contains a single integern (1 ≤ n ≤ 109).

Output

Print the requested sum for each of t integersn given in the input.

Sample test(s)
Input
2
4
1000000000
Output
-4
499999998352516354
 
    
 
    
题意:给出一个数n,计算1--n的和,但2的所有次方的数(如2^0,2^1...2^k<=n)需看成负数,即减去该数,最后的出结果。
 
    
思路:没必要用等比数列公式求,还是直接暴力好。求出负数和的绝对值minus,再用1--n的和sum减去minus,就得到需要累加的正数positive,
 
    
     用positive-minus即得到结果。
 
    
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
using namespace std;
int main()
{
#ifdef OFFLINE
	freopen("t.txt","r", stdin);
#endif
	ll t, i, n, sum, minus, positive;
	scanf("%lld", &t);
	while(t--){
		scanf("%lld", &n);
		sum=n*(n+1)/2;//1--n的和
		minus=1;//2^0
		for(i=2;i<=n;i*=2){
			minus+=i;
		}
		positive=sum-minus;//正数
		printf("%lld\n", positive-minus);
	}
	return 0;
}

你可能感兴趣的:(水题,CF)