# 64.求1+2+…+n

### 一、 题目

求 1+2+...+n ，要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句（A?B:C）。

示例 1：

输入: n = 3

输出: 6

示例 2：

输入: n = 9

输出: 45

限制：

1 <= n <= 10000

来源：力扣（LeetCode）

链接：<https://leetcode-cn.com/problems/qiu-12n-lcof>

著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

### 二、 解法

分析

* 因为有限制条件，我们就不能直接使用公式：Sn = n \* (n + 1) / 2 或 Smn=(n+m)(n-m+1)/2
* 可以使用递归代替循环

```
func sumNums(_ n: Int) -> Int {
    if n == 0 { return 0 }
    return n + sumNums(n - 1)
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/shu-ju-jie-gou-yu-suan-fa/jian-zhi-offerswift/64.-qiu-1+2++n.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
