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
#include<stdio.h>
int main()
{
int n,sum,i;
while(scanf("%d",&n)==1)
{
sum=n/2.0*(n+1);
printf("%d\n\n",sum);
}
return 0;
}
该题比较简单,循环一个一个数相加没什么问题。
但是,用sum(n)=n*(n+1)/2 公式计算可能会出错。原因是虽然最后的sum在32bit整数范围内,但是n*(n+1)可能会溢出。因此,有两种解决方法
1、将sum定义为__int64类型
2、sum=n/2.0*(n+1)。只能是2.0,不能是2,计算结果不可以中途舍掉小数部分。
3、通过此题可以发现当n为正整数时,n*(n+1)为偶数。