当前位置:网站首页>Two ways to find the factorial of n
Two ways to find the factorial of n
2022-08-09 17:48:00 【I'm free*】
Table of Contents
1. Method 1
Use a non-recursive approach
n!=1*2*3*...*n; Using for can solve this problem
//non-recursive#include int main(){int i = 0;int n = 0;int sum = 1;//sum is initialized to 1, not 0scanf("%d", &n);for (i = 1;i <= n;i++){sum = sum * i;}printf("%d!=%d", n, sum);return 0;}
2. Method 2
adoptedRecursive method
Text Explanation:
//Recursive
//n!=1*2*3*...*n
//get(1*2*3*...(n-1)) * n
//get(1*2*3*...(n-2))*(n-1)* n
//...
//get(1*2) 3* ... *(n-2) *(n-1)* n
//1*2...*(n-1)*n
Image explanation:
Example: Find the factorial of 5p>
Complete code map:
Analytical Diagram:
#include int get(int n){if(n>1){return n * get(n - 1);}else if(n == 1){return 1;}}int main(){//int n = 0, sum = 0;printf("Please enter a number: ");scanf("%d", &n);sum = get(n);printf("%d!=%d", n, sum);return 0;}
边栏推荐
猜你喜欢
随机推荐
字符菱形的代码
如何设置边框圆角
“泰迪杯”数据分析职业技能大赛B题 学生校园消费行为分析---复盘
第四章:使用本地地理空间数据(4.6-4.14)
The first day of the real in CSDN
Win10 Runas 命令 域用户以管理员权限运行
(一)BFC
Xshell显示乱码
RAID磁盘阵列详解
QT程序设计多人聊天室(基于QT、sqlite3、TCP/IP)
经典题型(一)
设计一个登录小程序(while和getchar实现)
Mysql学习(三)
2022深圳杯D题思路:复杂水平井三维轨道设计
Go语言基础(十一):反射
继承和选择器的权重
字典树、并查集相关:实现Trie、搜索推荐系统、朋友圈、被围绕的区域(未做) ...
学习编程的第四天
2022高教社杯 国赛数学建模 B题思路
js中的Date对象 及 将时间戳转换为yy-mm-dd hh:mm:ss格式的方法