Problem descriptionin this problem, your task is to calculate sum (n) = 1 + 2 + 3 +... + N. inputthe input will consist of a series of integers n, one integer per line outputfor 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 input1
100 sample output1
5050
GHOST:
#include<stdio.h>
int main()
{
int n,sum;
while(scanf("%d",&n)!=EOF)
{
sum=n*(n+1)/2;
printf("%d\n\n",sum);
}
return 0;
}
The brute force addition method can also be used. But those who have heard the story of "Prince of mathematics" Gauss should all know the "First n items and formulas", right? This was observed by Gauss at the age of 10. To make the code concise, I used the formula for solving the problem. The core is the sum = N * (n + 1)/2 in the above Code. During my local test, the entire process of output data is complete. However, the above Code is always wa (wrong answer) after the OJ submit.
I am speechless. And then find and find ....... Two hours later, I finally knew where the problem was.
It may overflow during N * (n + 1) multiplication. You may assume the result will be in the range of 32-bit signed integer. The result must be a 32-bit signed integer. The sum result of the test data given by OJ (N * (n + 1)/2) must be within the 32-bit integer range, but (N * (n + 1 )) not necessarily. We can infer that the reason for WA should be this. You can cleverly change the formula:
Set
Sum = N * (n + 1)/2;
Change
If (N % 2 = 0) // even
Sum = n/2 * (n + 1 );
Else // odd
Sum = (n + 1)/2 * N;
The Code is as follows:
#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;
}
Then you can get the desired AC. Congratulations ~ I was almost killed by this question, sorry.