ACM INTRODUCTION Hangzhou Electric 1001 questions about overflow considerations

Source: Internet
Author: User

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

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.