求1+2+3+...

GitHub跳转原题关系图返回列表

用递归求 1..N 的和:明确参数、出口 n=0、转移 n+sum_to(n-1) 三要素,调用链是一条直链,时间与栈空间均为 O(N)。

OJ: roj

题目 ID: 1158

难度:入门

标签:递推递归python

创建: 2026-09-29 21:25

更新: 2026-10-05 03:50

题目描述

给定整数 NN,用递归的方法求 1+2+3+⋯+N1+2+3+\cdots+N 的值。

输入一行整数 NN,输出一行累加和。输入样例 5 输出样例 15。

数据范围:1⩽N⩽131 \leqslant N \leqslant 13。

思路

递归三要素:参数是当前上界 nn,出口是 n=0n=0 返回 00,转移是 n+sum_to(n−1)n+\text{sum\_to}(n-1)。递归深度为 NN,时间与栈空间都是 O(N)O(N)。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 21:25
# update_at: 2026-09-29 21:25

import sys
from functools import cache


@cache
def sum_to(n: int) -> int:
    """返回 $1+2+\\cdots+n$:边界是 n == 0 时和为 0。"""
    return 0 if n == 0 else n + sum_to(n - 1)  # 未到边界就交给 n-1 层累加


def solve() -> None:
    data = iter(map(int, sys.stdin.buffer.read().split()))
    n = next(data)  # 题面唯一的整数 N

    print(sum_to(n))


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-05 03:50
 * update_at: 2026-10-05 03:50
 */
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

ll n;

// 递归求 1+2+...+n:边界 n==0 返回 0;否则本层认领 n,把 n-1 交给下一层。
ll sum_to(ll n) {
    if (n == 0) return 0;
    return n + sum_to(n - 1);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n;
    cout << sum_to(n) << '\n';

    return 0;
}