关闭

hdu 1001

309人阅读 评论(0) 收藏 举报
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;
}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:11626次
    • 积分:244
    • 等级:
    • 排名:千里之外
    • 原创:14篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条