您的位置:首页 > 编程语言 > C语言/C++

关于HDU1001的问题分析

2015-04-15 14:53 281 查看
题目如下:

Problem Description

Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).

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<iostream>

using namespace std;

int main()
{
int n;
while(cin>>n)
{
int sum=0;
for(int i=1;i<=n;i++)
sum+=i;
cout<<sum<<endl<<endl;
}
return 0;
}当然,也可以使用等差数列计算公式Sn=(a1+an)*n/2
然而,这里有个小细节需要注意,虽然Sn在int范围内,但是(a1+an)*n却可能溢出,为了确保这样的事情不发生,我们将这个等差数列公式一分为2处理。

首先可以知道的是a1+an和n都不会越界,所以我们可以考虑先计算(a1+an)/2,或者n/2,然而这两者之中肯定有一个是奇数,有一个是偶数,所以我们要在其中使用一个判断。

代码如下:

#include<iostream>
using namespace std;

int main()
{
int n;
while(cin>>n)
{
if((1+n)%2==0)
cout<<(1+n)/2*n<<endl<<endl;
else
cout<<n/2*(1+n)<<endl<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ ACM