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.
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);}}
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- 1001
- button_press.xml 按钮点击/未点击 两个不同效果
- 跟踪路由
- 写js中发现的各种不兼容
- TCP/IP网络协议学习笔记二
- Date、String、Timestamp之间的转换
- 1001
- 11.10彻底卸载 UNITY和UNITY 2D,安装配置GMONE3 Classic,自定义面板。
- Android开发之ListView 适配器(Adapter)优化
- 8、WEB开发由浅入深系列BLOG-8(JSTL标准标签库之FMT标签)
- 使用PICC预定义EEPROM数据的内容
- spss Clementine12 免费破解版
- Android实现程序前后台切换效果(类似QQ后台运行)
- 调试跟踪Android源代码
- ELF 文件格式常见段名称及自定义段