[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 216. Combination Sum III
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
79 0
LeetCode 216. Combination Sum III
LeetCode 39. Combination Sum
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。
55 0
LeetCode 39. Combination Sum
LeetCode 64. Minimum Path Sum
给定m x n网格填充非负数,找到从左上到右下的路径,这最小化了沿其路径的所有数字的总和。 注意:您只能在任何时间点向下或向右移动。
69 0
LeetCode 64. Minimum Path Sum
HDOJ 2058 The sum problem
HDOJ 2058 The sum problem
89 0
HDOJ 1001Sum Problem
HDOJ 1001Sum Problem
93 0
|
机器学习/深度学习
HDOJ-1001 Sum Problem
Problem Description Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).
1235 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
LeetCode - 39. Combination Sum
39. Combination Sum  Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个待选集合s和一个数n,让你找出集合s中相加之和为n的所有组合.
806 0
LeetCode - 40. Combination Sum II
40. Combination Sum II  Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个待选集合s和一个数n,选出所有相加之和为n的组合.
971 0