1001

来源:互联网 发布:阿里云服务器能做什么 编辑:程序博客网 时间:2024/04/26 01:38
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
1100
 

Sample Output
15050


第一版代码:

#include <iostream>using namespace std;int sum(int n){int a = 1;int m=0;while(a<=n){m+=a;a++;}return m;}int main(){int n;while(cin>>n){cout<<sum(n)<<endl<<endl;}return 0;}

第二版,递归实现

#include <stdio.h>int sum(int n){if (n==1){return 1;}elsereturn n+sum(n-1);}int main(){int n;while(scanf("%d",&n) != EOF){printf("%d\n\n",sum(n));}}

递归实现时使用的额外空间过大,进行如下改进:

#include <stdio.h>int main(){int n,m;while(scanf("%d",&n) != EOF){m=0;while(n){m+=n--;}printf("%d\n\n",m);}}



原创粉丝点击