算法与数据结构 · 实战

1001 Sum Problem

本文写于 2021 年,涉及的组件版本、配置与数据可能已过时,请按经验材料阅读并核对当前版本。原文链接与内容保持不变。

题目信息

Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 745568 Accepted Submission(s): 188863

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

题解

C语言解法

#include <stdio.h>

int main() {
    int m;
    while (EOF != scanf("%d", &m)) {
        // it not work
        // printf("%d\n\n", m*(m+1)/2);
        int s = 0;
        for (int i = 1; i <= m; i++) {
            s += i;
        }
        printf("%d\n\n", s);
    }
    return 0;
}

Be Careful

  • 输出结果后要两个换行.
  • 这道题一定不要使用等差数列求和。因为n*(n+1) 会超时 int 类型数值范围。

长点心吧

[面前有两条路,中规中矩and捷径,是鼓励走捷径的。但是一定要确定捷径的结果是和另一条路是一模一样的。否则还是选择中规中矩的路吧。否则是会付出代价的。你怎么知道捷径是不是一条不归路呢?]{.label .warning}

链接

相关链接

最后

希望与你一起遇见更好的自己

期望与你一起遇见更好的自己

配套资料 · 免费领取
本文属于「ALGO」资料包范围:算法系列合订 + 刷题清单。LeetCode 与杭电 OJ 的题解索引。
在公众号「方家小白」回复关键词 ALGO 即可领取。全文无需关注即可阅读。
ALGO