1001 Sum Problem

来源:互联网 发布:自学电脑编程最快多久 编辑:程序博客网 时间:2024/06/13 23:03

Sum Problem

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


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
1100
 

Sample Output
15050

这个题是求自然数前n项的和,结果在int 范围内,有两种处理方法,一个是循环累加,一个是求和公式,下面我用的是求和公式.....

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

提交上去,wrong answer!!

为什么,想来想去,才发现这个程序的漏洞,你想到了吗?输个五万(50000)上去试试就知道了......

就是说,数据结果不超过int 但是中间过程可能超过int ,这里有两种方法解决

1,用long long 型运算,2,用另外一种方法.......

这样的方法可以防溢出,不懂的话,好好想想为什么,想通了的确对自己有帮助,这是个很好的思想..嘿嘿

#include<stdio.h>int main() {int a,b;while(scanf("%d",&a)!=EOF){b=(a%2)?((a+1)/2*a):(a/2*(a+1));printf("%d\n\n",b);}return 0;}




0 0