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 i,n,sum; while(scanf("%d",&n)==1) { sum=0; for(i=1;i<=n;i++) sum+=i; printf("%d ",sum); } return 0; }
或者
#include <stdio.h> int main() { int i,n,sum; while(scanf("%d",&n)!=EOF) { sum=0; for(i=1;i<=n;i++) sum+=i; printf("%d ",sum); } return 0; }
但是在网上找了一下,发现别人说这种暴力加法有时候很有可能超过内存限制,所以提高C程序运行效率的方式就是能用数学公式就尽量用。
但是只是把加法换成公式这么简单吗?
sum=n*(n+1)/2;
提交WA,为什么呢?
原因就在于题目上说n和sum是32位整形数据,但是n*(n+1)很有可能就爆了。所以得再加以修改。
#include <stdio.h> #include <stdlib.h> int main() { int n,sum; while(scanf("%d",&n)!=EOF) { if(n%2) sum=(n+1)/2*n; else sum=n/2*(n+1); printf("%d ",sum); } return 0; }
另外有一个小坑follow a blank line。所以我们得用两个换行符。。。