A. Tricky Sum
time limit per test
1 secondmemory limit per test
256 megabytesinput
standard inputoutput
standard outputIn 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; }
该问题要求计算从1到n的所有整数的和,但2的幂次要在总和中取负。例如,当n=4时,和为-1-2+3-4=-4,因为1, 2和4分别是2的0次、1次和2次幂。输入包含t个待处理的n值,每个n值在1到10^9之间。对于每个n,输出对应的经过特殊计算的和。"
109335873,5682910,RocketMQ核心概念解析,"['消息队列', '分布式', '消息消费', '存储', '事务']
137

被折叠的 条评论
为什么被折叠?



