Recently in the attempt to do ACM test, just 1001 of the questions have trapped me, this is the topic:
Problem DescriptionIn This problem, your task was to calculate SUM (n) = 1 + 2 + 3 + ... + N. inputthe input would consist of A series of integers n, one integer per line outputfor each case, output SUM (n) on one line, followed by a blank line. You may assume the result is in the range of 32-bit signed integer. Sample Input1 100Sample Output1 5050
1#include <stdio.h>2 intMain ()3 {4 intn,sum;5 while(SCANF ("%d", &n)! =EOF)6 {7Sum= (n+1) *n/2;8printf"%d\n\n", sum);9 }Ten}
Initially thought the topic is very simple, if the direct violence sums, is possible, but I have learned arithmetic progression's summation formula, this is the Gauss 10 years old discovery. For the sake of brevity, I use the formula method to solve. When testing locally, the output data is completely correct. However, the above code on hang power after the submit always wa (wrong Answer) off.
I have no words. Then a long time to think about the reason, finally after I Baidu to know where the problem.
When n (n+1) is multiplied, it overflows. The title asks "may assume the result is in the range of 32-bit signed integer", which requires that the sum is a 32-bit signed integer. The sum of the test data given by OJ (n (n+1)/2) must be within the range of 32-bit integers, but (n (n+1)) is not necessarily. The reason you can infer WA should be here. You can subtly change the formula:
Put
sum=n* (n+1)/2;
Switch
if (n%2==0)
sum=n/2* (n+1);
Else
Sum= (n+1)/2*n;
The entire code is as follows:
1#include <stdio.h>2 intMain ()3 {4 intn,sum;5 while(SCANF ("%d", &n)! =EOF)6 {7 if(n%2==0)8sum=n/2* (n+1);9 ElseTenSum= (n+1)/2*N; One Aprintf"%d\n\n", sum); - } -}
Then you can get the AC. I was almost killed by this water problem.
ACM INTRODUCTION Hangzhou Electric 1001 questions about overflow considerations