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

从零开始刷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;
}
发布了40 篇原创文章 · 获赞 0 · 访问量 5160

猜你喜欢

转载自blog.csdn.net/edward00324258/article/details/72542377
今日推荐