[ACMcoder] Sum Problem

简介: 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

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, sum;
    while (cin>>n)
    {
        sum = (n+1)/2.0*n;
        cout<<sum<<endl<<endl;
    }
    return 0;
}

对于这道水题,也真是醉了,如下代码竟然WA:

#include <iostream>
using namespace std;

int main()
{
    int n;
    while (cin>>n)
        cout<<(n+1)/2.0*n<<endl<<endl;

    return 0;
}
目录
相关文章
LeetCode 39. Combination Sum
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。
55 0
LeetCode 39. Combination Sum
LeetCode 216. Combination Sum III
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
79 0
LeetCode 216. Combination Sum III
A1947 An Olympian Math Problem
Alice, a student of grade 66, is thinking about an Olympian Math problem, but she feels so despair that she cries. And her classmate, Bob, has no idea about the problem. Thus he wants you to help him. The problem is:
59 0
A1947 An Olympian Math Problem
HDOJ 2058 The sum problem
HDOJ 2058 The sum problem
89 0
HDOJ 1001Sum Problem
HDOJ 1001Sum Problem
92 0
|
机器学习/深度学习
HDOJ-1001 Sum Problem
Problem Description Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).
1234 0
LeetCode 216 Combination Sum III(Backtracking)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/51935033 翻译 找出所有的k个数字相加得到数字n的组合,只有1到9的数字可以被使用,并且每个组合间需要是不同的数字集。
714 0