The Sum of 1...N

The Sum of 1...N

时间: 1ms        内存:128M

描述:

Given an integer n,your task is to calculate 1+2+...+N;

输入:

The first line of input contains an integer T, indicating the number of test cases (T<=20)

The each test case contains a single positive integer N(N<=2^32).

输出:

For each input you should output the sum of 1+2+...+N in one line.(The result must less than 2^63)

 

示例输入:

2
10
1

示例输出:

55
1

提示:

参考答案(内存最优[1092]):

#include<stdio.h>
int main()
{
    int m,i;
    unsigned long long  n;
    scanf("%d",&m);
    for(i=0;i<m;i++)
    {
    scanf("%lld",&n);
    n=(n*(n+1))/2;
    printf("%lld\n",n);
    }
    return 0;
}

参考答案(时间最优[0]):

#include <iostream>
using namespace std;
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        long long n;
        cin>>n;
        if(n&1)
        {
            n=((n+1)>>1)*n;
        }
        else
        {
            n=(n>>1)*(n+1);
        }
        cout<<n<<endl;
    }
    return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注