Problem Description
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
這道題真心坑,我一開始想到的是用高斯求和的方法,也就是等差數列求和,d=1的情況。由於我誤會有兩個輸入,所以表達式就是sum=(m+n)*(n-m+1)/2,但是題目的意思應該是每一行只輸入一個整數n,計算1累加到n的總和,因此將上式的m賦值爲1,得出公式爲sum=(n+1)*n/2,當我欣喜地發現是我理解錯題目並submit後,總是WA,我也是很心痛的。
#include <stdio.h>
int main() {
int m,n;
while(scanf("%d",&m)!=EOF)
{
scanf("%d",&n);
printf("%d\n",(m+n)*(n-m+1)/2);
}
return 0;
}
找了很久的錯誤,發現題目中有一句要求是求和結果是32位有符號整數。那麼問題來了,結果(n+1)*n/2一定是32位整數範圍內的,但是(n+1)*n就不一定了。因此我們可以先除再乘來解決這個問題。修改後的代碼如下:
Submission
#include<stdio.h>
int main()
{
int n,sum;
while(scanf("%d",&n)!=EOF)
{
if(n%2==0)
sum=n/2*(n+1);
else
sum=(n+1)/2*n;
printf("%d\n\n",sum);
}
return 0;
}
還有一種方法就是採用累加法,是可以AC的,如下:
#include<stdio.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i;
int sum=0;
for(i=1;i<=n;i++)
sum+=i;
printf("%d\n\n",sum);
}
return 0;
}