杭电OJ-1001

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yuzhiping1/article/details/79222637
Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).
In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.
The input will consist of a series of integers n, one integer per line.

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)/2 一旦n过大 就会产生溢出。 所以可以提前对n 或n+1 进行除2

#include<stdio.h>
int main()
{
long n;
while(scanf("%ld",&n)!=EOF)
{
if(n%2==0)
printf("%ld\n\n",n/2*(n+1));
else printf("%ld\n\n",(n+1)/2*n);
}
}


猜你喜欢

转载自blog.csdn.net/yuzhiping1/article/details/79222637