hdu1001 Sum Problem 差点被这个题玩死了

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
 
-------------------------------------------------------------------------------------------------------------------------------
 
      看看玩死我的代码:
#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;
}

      如果用暴力加法呢,也是可以算出来的。但是听过“数学王子”高斯的故事的人应该都知道“前N项和公式”吧?这是高斯10岁时的发现。为了代码简洁,我采用了公式法求解。核心就是上述代码中的sum=n*(n+1)/2这句。我在本地测试时,输出数据完全程却。但是呢,上边代码在OJ上submit之后总是WA(Wrong Answer)掉。

      我就无语了。然后找啊找啊找啊找啊。……2个小时之后,我终于知道问题出在哪里了。

      可能在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;

     整个代码如下:

#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;
}

      接着就可以如愿以偿的AC了。恭喜了~被这个水题差点玩死了,囧啊。


 

 
posted @ 2011-07-20 17:04  ErinFlyingFish  阅读(15103)  评论(4编辑  收藏  举报