tctony

Focus on linux,emacs,c/c++,python,algorithm...

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  17 随笔 :: 0 文章 :: 7 评论 :: 0 Trackbacks

Sum Problem

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


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


此题仍属简单计算题。有两种方法
1.循环加法完成

#include<iostream>
using namespace std;

int main () 
{
    
int i,n,sum;
    
while(cin>>n){
        
for(i=1,sum=0;i<=n;i++)
            sum
+=i;
        cout
<<sum<<endl<<endl;
    }

    
return 0;
}
2.乘法公式(n*(n+1)/2)一步到位。快,是否稳?显然题中只说(n*(n+1)/2)的最后结果在int范围内不溢出,显然中间过程n*(n+1)就无法保证,故有如下算法
#include<iostream>
using namespace std;

int main()
{
    
int n;
    
while(cin>>n){
        
if(n%2==0)
            cout
<<(n/2)*(n+1)<<endl<<endl;
        
else
            cout
<<n*((n+1)/2)<<endl<<endl;
    }

    
return 0;
}


最后需要注意的是输出格式,每输出一个结果,后面跟着输出2个换行符。
posted on 2007-11-28 13:14 tctony 阅读(1088) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理