当前位置:网站首页>n的阶乘
n的阶乘
2022-07-21 05:15:00 【龙星尘】
今天,我学习了递归算法的第一课,介绍了关于递归的基本思想:“在一个函数里调用这个函数,就是递归算法”。
第一题是编写一个函数,运用递归算法,来写出n的阶乘加起来是什么。
输入
一个正整数n
输出
一行,表示n的阶乘
输入样例1:
4
输出样例1:
24
输入样例2:
11
输出样例2:
39916800
我的代码1:
#include <iostream>
using namespace std;
int jiecheng(long long n)
{
if(n==0)
return 1;
return n*jiecheng(n-1);
}
int main()
{
long long n;
cin>>n;
cout<<jiecheng(n)<<endl;
}
每次将n-1,减到n==0为止,就return 1;停止函数运行,最后将返回的值 cout输出,就可以算出n的阶乘了!
除了这个方法,我们还有一个方法,这个方法我们是从n-1依次减,第二种方法我们可以从1开始n+1,为什么要从1开始呢?因为从0开始的话,任何数乘0都为0,所以我们要从1开始
我的代码2:
#include <iostream>
using namespace std;
long long a;
int jiecheng(long long n)
{
if(n==a+1)
return 1;
return n*jiecheng(n+1);
}
int main()
{
cin>>a;
cout<<jiecheng(1)<<endl;
}
因为是从1开始的,函数结束的条件要变化,由于从1开始,我们要如果等于a+1的话停止,由于判断条件不是等于0,要新增加一个变量a。
这就是递归中最简单的基础题,我们用两种方法就成功了,下一期我会带来更有难度的题目哦。
边栏推荐
- Source insight 4.0 personalization and shortcut keys
- 组队
- Learn SCP NFS TFTP together
- 06-Page Object+pytest单元测试框架
- 04-unittest單元測試框架
- Teach you how to use yolov4 training and testing data set on the server (nanny level)
- 01背包面试题系列(一)
- Do you really understand the 01 backpack problem? Can you answer these questions of 01 backpack?
- Verification code is the natural enemy of automation? See how the great God solved it
- . Net memory leakage causes and Solutions
猜你喜欢
西瓜书第二章笔记-性能度量
Principles and advantages of wireless charging module development
Smart devices are coming, making our lives more automated
Built in WiFi and Bluetooth chip of Flathead brother xuantie
567. 字符串的排列
Do you think sub database and sub table are really suitable for your system? Talk about how to select sub databases, sub tables and newsql
What is the gateway? What is the Internet of things gateway?
3级学业水平测试
In depth analysis of multiple knapsack problem (Part 2)
Using UUID as MySQL primary key, my boss broke up
随机推荐
. Net memory leakage causes and Solutions
Heap - principle to application - heap sort, priority queue
Using two templates (recursive method and iterative method) to complete four traversal ways of binary tree
Appium+pytest+allure realizes app automated testing, which is a small test
Source insight 4.0 personalization and shortcut keys
Pytorch2onnx2tensorflow environment preparation win10
01 knapsack interview questions series (I)
Yolov4 (Darknet version) post processing: display confidence and save the contents of the detection box locally
概率论-最大似然估计
Learn multithreading, process and development board together
The 22 pictures show you in-depth analysis of prefix, infix, suffix expressions and expression evaluation
Deep analysis of fiboracci sequence
01背包面试题系列(一)
Easily self-made Pascal VOC dataset
西瓜书第三章-线性模型
Do you really understand the 01 backpack problem? Can you answer these questions of 01 backpack?
datart 开源数据可视化应用 | 手把手教你开发出优秀的图表插件
3级学业水平测试
Do you think sub database and sub table are really suitable for your system? Talk about how to select sub databases, sub tables and newsql
04 cadre d'essai de l'unit é unitest