当前位置:网站首页>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;} 
边栏推荐
猜你喜欢
随机推荐
标准IO及其各函数用法
Heap series_0x08: NT heap debug support_Discover now debug support (DPH)
js实现滑动条验证
字符菱形的代码
第二章:创建交互式地图(2.1-2.3)
Heap series_0x06: NT global flags and gflags.exe one page
WinServer 2019 组策略删除本地管理员且只允许域用户登陆
C语言冒泡排序法
2022华数杯建模A题思路解析
选择器的使用
properties文件的读取和写入
第二章:创建交互式地图(2.4-2.6)
2022高教社杯 国赛数学建模 D题思路
List,Set,Map,Queue,Deque,Stack遍历方式总结
2022高教社杯 国赛数学建模 A题思路
学习编程的第四天
单臂路由与三层交换机实现跨VLAN通讯
0. About The Author And Preface
2022华数杯建模B题思路解析
求n的阶乘的两种方法









