1001 Sum Problem

Sum Problem

Time Limit: 1000/500 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 387857    Accepted Submission(s): 97127


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.
 
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
1 100
 
Sample Output
1 5050
 
 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     int n,sum;
 8     while(cin>>n)
 9     {
10         if(n%2!=0)
11         sum=(1+n)/2*n;
12         else
13         sum=(1+n)/2*n+n/2;
14         cout<<sum<<endl;
15         cout<<endl;
16     }
17     return 0;
18 }

注意!!注意!!!

以为是一个很简单的问题,但会不小心的把(You may assume the result will be in the range of 32-bit signed integer.)给忽略掉,当n*(n-1)时是会溢出的。

原文地址:https://www.cnblogs.com/wang-ya-wei/p/5132507.html