关于HDU1001的问题分析

题目如下:

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值