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
1
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
读到题目的第一想法就是用数学公式 SUM(n) = (1 + n) * n / 2 ;但是,提交后却无法通过,后来才发现题目要求是32bit,但是 (1 + n) * n 可能会超出范围,所以先除以2,就得考虑奇偶问题。代码如下:
#include<iostream>
using namespace std;
int main(){
int n;
while(cin>>n){
if(n%2 == 0) //注意:题目要求不能超出32bit,但是n*(n+1)会超出范围,所以的先除2!
{cout<<(n/2)*(n+1)<<endl<<endl;}
else
{cout<<((n+1)/2)*n<<endl<<endl;}
}
return 0;
}