acm入门 杭电1001题 有关溢出的考虑

最近在尝试做acm试题,刚刚是1001题就把我困住了,这是题目:

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
 1 #include<stdio.h>
 2 int main() 
 3 {
 4     int n,sum;
 5     while(scanf("%d",&n)!=EOF)
 6     {
 7         sum=(n+1)*n/2;
 8         printf("%d

",sum);
 9     }
10 }
 
刚开始认为题目很简单,如果直接暴力求和,是可以的,但是我门学过等差数列的求和公式,
这是高斯10岁时的发现。为了代码简洁,我采用了公式法求解。在本地测试时,输出数据完全正确。但是,上边代码在杭电上submit之后总是WA(Wrong Answer)掉。
 
 

 我就无语了。然后很长时间想不出原因,最后经过我百度一下才知道问题出在哪里。

      在n*(n+1)乘法的时候,会溢出。题目要求“You may assume the result will be in the range of 32-bit signed integer ”,要求的是求和结果是32位有符号整数。OJ给出的测试数据的求和结果(n*(n+1)/2)一定是32位整数范围内的,但是(n*(n+1))就不一定了。可以推断WA的原因应该在此。可以将公式巧妙地变动一下:

  把

sum=n*(n+1)/2;

  改为

    if(n%2==0) 

      sum=n/2*(n+1);

    else 

      sum=(n+1)/2*n;

     整个代码如下:

 1 #include<stdio.h>
 2 int main() 
 3 {
 4     int n,sum;
 5     while(scanf("%d",&n)!=EOF)
 6     {
 7         if(n%2==0)
 8             sum=n/2*(n+1);
 9          else
10             sum=(n+1)/2*n;
11 
12         printf("%d

",sum);
13     }
14 }

接着就可以如愿以偿的AC了。感觉被这个水题差点玩死了- -.

原文地址:https://www.cnblogs.com/kpxy/p/5654205.html