Hdu1001 sum problem was almost killed by this question.

Source: Internet
Author: User
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.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.