杭电acm1001
Sum Problem
Problem Description
Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).
In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.
In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.
Input
The input will consist of a series of integers n, one integer per line.
Output
For each case, output SUM(n) in one line, followed by a blank line.
注意:You may assume the result will be in the range of 32-bit signed integer.
Sample Input
1100
Sample Output
15050
Author
DOOM III
实现代码:
#include <iostream>
using namespace std;
int main()
{
int n,sum;
while(cin>>n)
{
//为什么要sum结果是一样,却分开写呢?因为看上面的注意,可能在n*(n+1)乘法的时候,会溢出。
//看这句要求“You may assume the result will be in the range of 32-bit signed integer ”,要求的是求和结果是32位有符号整数。
//OJ给出的测试数据的求和结果(n*(n+1)/2)一定是32位整数范围内的,但是(n*(n+1))就不一定了。
if(n%2 == 0)//偶数
sum = n/2*(n+1);
else//奇数
sum = (n+1)/2*n;
cout<<sum<<endl;
cout<<endl;
}
return 0;
}