從零開始刷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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章