用递归函数表达 n! = n * (n-1)!,在 n=1 时返回 1。
OJ: luogu
题目 ID: P5739
难度:入门
标签:递归数学函数python
日期: 2026-07-15 21:08
题意
输入一个正整数 n,输出 n!。题目挑战尝试不使用循环完成。
思路
阶乘的递归定义是:
text
1! = 1
n! = n * (n-1)! (n > 1)把这个定义直接写成函数:
python
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)因为 n <= 12,递归深度很小,不需要调整递归限制。
这题是递归函数练习,不创建 brute.py。
Python 知识
/home/rainboy/mycode/hugo-blog/content/program_language/python/math_tools.md:Python 整数不会溢出,适合直接计算小范围阶乘。/home/rainboy/mycode/hugo-blog/content/program_language/python/input_output_and_strings.md:单个整数输入用int(input())。- 递归函数必须有明确的终止条件,否则会无限调用。
- Python 函数用
return把计算结果交回上一层。
代码
python
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
n = int(input())
print(factorial(n))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-07-27 00:00
* update_at: 2026-07-27 00:00
*/
#include <bits/stdc++.h>
using namespace std;
// 递归计算阶乘:n! = n * (n-1)!
int fact(int n) {
if (n == 1) return 1; // 终止条件
return n * fact(n - 1); // 递归调用
}
int main() {
int n;
cin >> n;
cout << fact(n);
return 0;
}Pythonic 写法
math.factorial:
python
from math import factorial
print(factorial(int(input())))复杂度
递归调用 n 层,时间复杂度是
总结
递归适合直接表达“当前问题依赖更小的同类问题”。阶乘是最基础的递归例子:先写终止条件,再写递推关系。