您的位置:首页 > 编程语言 > C语言/C++

从零开始刷HDOJ(2)【HDOJ1001 - Sum Problem】

2017-05-19 16:45 387 查看

从零开始刷HDOJ(2)【HDOJ1001 - Sum Problem】

题面

Sum Problem

Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

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


Author

DOOM III

Recommend

We have carefully selected several similar problems for you: 1002 1090 1003 1091 1004

Statistic | Submit | Discuss | Note

翻译

​ 每行输入一个数,然后隔一行输出一个数,这个数是从1加到输入的那个数的和。

思路

​ 循环?肯定是不行啊,因为每一行的输入都是32位的。所以,应该用到一个众所周知的公式——

∑i=1ni=n(n+1)2

​ 所以,每一个数都可以O(1)求了。

代码

#include <iostream>

int main(int argc, char ** argv)
{
std::ios_base::sync_with_stdio(false);
long long x;
while (std::cin >> x)
std::cout << x * (x + 1) / 2 << std::endl << std::endl;
//底下就是暂停用的,不用管。
#ifdef __EDWARD_EDIT
std::cin.get();
std::cin.get();
#endif
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDOJ ACM 算法 C++