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
其实这个题是个水题,但是也有几个地方需要注意;用高斯的方法进行计算时,不能先用n*(n+1),因为他会大于32位整数的范围。所以应该分奇偶数来讨论。
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int n;
int sum;
while(~scanf("%d",&n)){
if(n%2==0)
sum=n/2*(n+1);
else sum=(n+1)/2*n;
printf("%d\n",sum);
printf("\n");
}
return 0;
}