当前位置:网站首页>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;}
边栏推荐
猜你喜欢
随机推荐
(十)打包和项目部署
js事件流
超文本链接
2022华数杯建模A题思路解析
(七)小思同学和性能
Redis学习(一.redis中的数据结构)
2021深圳杯A题思路 火星探测器着陆控制方案
学习编程的第四天
辨析fork与vfork
Go语言基础(十四):单元测试
详解VLAN与划分广播域
Codeforces Round #808 (Div. 2)||沉淀
Redis learning (1. Data structure in redis)
学编程的第十天
Go语言基础(十二):并发编程
字符菱形的代码
第四章:使用本地地理空间数据(4.6-4.14)
The first day of the real in CSDN
MySQL必知必会(二)
字典树、并查集相关:实现Trie、搜索推荐系统、朋友圈、被围绕的区域(未做) ...