HDOJ 1001 Sum Problem 解题报告

Sum Problem

Time Limit: 1000/500 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 211295    Accepted Submission(s): 51266


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
 

 

Author
DOOM III
 
 
 
 
分析:
这题其实没有什么难度,
就是最简单的计算前N项和,
注意输出格式就好了。
 
 
 自己用C++写的:
Accepted
#include<iostream>
using namespace std; int main() { unsigned int a; while(cin>>a) cout<<(a+1)*a/2<<endl<<endl; return 0; }



觉得奇怪的是,一定要用无符号的数据类型才能通过,,不知道为什么。

下面的代码就是错误的。。。
真是不知道为什么???

Wrong Answer
#include<iostream>
using namespace std;
int main()
{
    int a;
    while(cin>>a)
    cout<<(a+1)*a/2<<endl<<endl;
    return 0;
}

下面的代码是用C来写的,用C写感觉更顺。

#include<stdio.h>
main()
{
int n;
while(scanf("%d", &n) != EOF) 
printf("%d\n\n", (n%2)?(n+1)/2*n:n/2*(n+1));

}
//(n%2)?(n+1)/2*n:n/2*(n+1)
这里貌似是一个天大的陷阱,如果不注意可能一直WA,,非常坑爹。

如果n为奇数的话,需要加1后再除以2,如果n是偶数,则直接除以2.




 
 
posted @ 2013-04-27 13:30  Geekers  阅读(329)  评论(0编辑  收藏  举报