CF--A. Tricky Sum

该问题要求计算从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核心概念解析,"['消息队列', '分布式', '消息消费', '存储', '事务']

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;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值