hdu1001 Sum proble 差点被这个题玩死

来源:互联网 发布:淘宝优惠券兼职靠谱吗 编辑:程序博客网 时间:2024/05/21 14:45
题目:
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
 
-------------------------------------------------------------------------------------------------------------------------------
 这个题目可以采用两种解法,第一种就是暴力解法,单纯的采用一个一个的加一,最后得到结果,第二种解法就是用前n项和的公式解法,本人第一次用的是公式解法,代码如下:
#include<iostream>
using namespace std;
int main()
{
int n,sum;
while(cin>>n)
{
  sum=n*(n+1)/2;
  cout<<sum<<endl;
}
return 0;
}
......................................................................................................................................
在vc上运行结果很正确,但上交是却出现错误,我那个郁闷啊,仔细看看,没错啊,反反复复实验,一个·多小时后,终于发现错误了。 You may assume the result will be in the range of 32-bit signed integer.这句话是我错误的关键,题目要求结果在32位整数以内,而n*(n+1)/2可能是小数,所以将代码稍微更改一下:
if(n%2==0)
sum=n/2*(n+1);
else sum=n*(n+1)/2;
结果再次上交,Accepted!这次正确了,浪费一个多小时才解出来,囧啊。










0 0
原创粉丝点击