关于HDU1001的问题分析
2015-04-15 14:53
281 查看
题目如下:
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;
else
cout<<n/2*(1+n)<<endl<<endl;
}
return 0;
}
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;
else
cout<<n/2*(1+n)<<endl<<endl;
}
return 0;
}
相关文章推荐
- 关于字体图标在firefox上本地访问无法显示的问题分析
- Android关于Theme.AppCompat相关问题的深入分析
- 九度OJ剑指offer中关于顺时针输出矩阵的问题分析
- 关于诺顿频繁查杀DWH*.TMP病毒的问题分析
- 关于形如--error LNK2005: xxx 已经在 msvcrtd.lib ( MSVCR90D.dll ) 中定义--的问题分析解决
- Android关于Theme.AppCompat相关问题的深入分析
- 关于spring定时器一次调用却触发了两次trigger的问题分析
- 关于block内存问题的分析
- 关于内网版网站建设的一些问题以及分析
- Android关于Theme.AppCompat相关问题的深入分析(转)
- 关于redis性能问题分析和优化
- Android关于Theme.AppCompat相关问题的深入分析
- 关于形如--error LNK2005: xxx 已经在 msvcrtd.lib ( MSVCR90D.dll ) 中定义--的问题分析解决
- 关于“不允许指针指向不完整的类类型”问题分析
- 关于淘宝商品如何定价问题分析
- 关于"建立空文档失败"的问题的分析
- 关于形如--error LNK2005: xxx 已经在 msvcrtd.lib ( MSVCR90D.dll ) 中定义--的问题分析解决
- 关于扩展 Laravel 默认 Session 中间件导致的 Session 写入失效问题分析
- 关于Linux下安装Oracle时报错:out of memory的问题分析说明
- 关于从NAND Flash启动的问题,2440 启动问题 , 拷贝4k程序 ,启动代码分析