hdu 1001
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


读到题目的第一想法就是用数学公式 SUM(n) = (1 + n) * n / 2 ;但是,提交后却无法通过,后来才发现题目要求是32bit,但是 (1 + n) * n 可能会超出范围,所以先除以2,就得考虑奇偶问题。代码如下:


#include<iostream>
using namespace std;
int main(){
int n;
while(cin>>n){
if(n%2 == 0) //注意:题目要求不能超出32bit,但是n*(n+1)会超出范围,所以的先除2!
{cout<<(n/2)*(n+1)<<endl<<endl;}
else
{cout<<((n+1)/2)*n<<endl<<endl;}
}
return 0;
}



阅读更多
个人分类: hud解题心历路程
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

hdu 1001

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭