关于HDU1001的问题分析
来源:互联网 发布:nginx 录播保存record 编辑:程序博客网 时间:2024/05/23 01:17
题目如下:
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
题目很简单,使用最简单得累加,代码如下:
#include<iostream>using namespace std;int main(){int n;while(cin>>n){int sum=0;for(int i=1;i<=n;i++)sum+=i;cout<<sum<<endl<<endl;}return 0;}当然,也可以使用等差数列计算公式Sn=(a1+an)*n/2
然而,这里有个小细节需要注意,虽然Sn在int范围内,但是(a1+an)*n却可能溢出,为了确保这样的事情不发生,我们将这个等差数列公式一分为2处理。
首先可以知道的是a1+an和n都不会越界,所以我们可以考虑先计算(a1+an)/2,或者n/2,然而这两者之中肯定有一个是奇数,有一个是偶数,所以我们要在其中使用一个判断。
代码如下:
#include<iostream>using namespace std;int main(){int n;while(cin>>n){if((1+n)%2==0)cout<<(1+n)/2*n<<endl<<endl;elsecout<<n/2*(1+n)<<endl<<endl;}return 0;}
0 0
- 关于HDU1001的问题分析
- HDU1001
- hdu1001
- HDU1001
- hdu1001
- HDU1001
- HDU1001
- hdu1001
- HDU1001
- HDU1001
- HDU1001
- hdu1001
- HDU1001
- HDU1001
- 【有关数的范围】[HDU1001]
- 关于static问题的分析
- 关于MATLAB图像相关性分析的问题
- 关于主成分分析的五个问题
- EXTJS 3 EXT容器布局(Fit,Card,Border)
- [c++]多继承
- mybatis学习之一对多查询如何避免只查出一条数据
- 通过手势切换屏幕的几种方法
- Nutch1.7二次开发培训讲义
- 关于HDU1001的问题分析
- 【python】随机数和日期
- 安卓5.0Intent打开相册选择图片无返回值问题
- 程序员修炼之路
- 关于Eclipse项目中加入jquery.js文件报错(missing semicolon)问题
- HDU 4609 3-idiots FFT
- SD-SD用到的文本对象列表
- android笔记整理
- java 数组使用和定义