CodeForces - 598A:求前n项和减去2的倍数的数(水题)

泰泰学长又来玩数字了,泰泰学长想让你帮他求1-n的和,但是这次的求和可不是简单的1+2+…+n。 这次的求和是这样的,如果加到一个数字是2的指数倍,那就不加,反而减掉这个数。
比如 n = 4:-1-2+3-4 = -4。
说明:其中1,2,4都是2的指数倍。
Input
第一行是总询问数 T,接下来T行,每行一个 n,(1<=T<=100)(1<=n<=10^9)
Output
输出对应的结果

Sample Input
2
4
1000000000
Sample Output

-4
499999998352516354

水题:先用公式将前n项和计算出来,然后减去前n项出现2的指数倍数的2倍

代码如下

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <math.h>

using namespace std;
typedef long long ll;
int main()
{
    int t;
    ll n,sum,x;
    scanf("%d",&t);
    while(t--)
    {
        sum = 0;
        scanf("%lld",&n);
        sum = n*(1+n)/2;
        int i = 0;
        x = 1;
        while(x <= n)
        {
            sum -= 2*x;
            i++;
            x = pow(2,i);
        }
        printf("%lld\n",sum);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43327091/article/details/87901935