关于HDU1001的问题分析

来源:互联网 发布:nginx 录播保存record 编辑:程序博客网 时间:2024/05/23 01:17

题目如下:

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;elsecout<<n/2*(1+n)<<endl<<endl;}return 0;}



0 0
原创粉丝点击