当前位置:网站首页>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;} 
边栏推荐
猜你喜欢
随机推荐
String的构造方法,其他方法
路由概述与静态配置ip
动态规划套题:不同路径
给我一个机会,帮你快速上手三子棋
Mysql学习(一)
2022华数杯A题 B题 C题 思路汇总
【中英文目录】导读
Mysql学习(二)
vmware workstation 未能启动vmware
华为防火墙相关命令
typescript学习(三)
VRRP详解与配置实例
Mysql学习(四)
第三章:GEE数据的使用(3.1-3.3)
JS字符串对象基础操作方法
QT程序设计多人聊天室(基于QT、sqlite3、TCP/IP)
Lens 创建 Service Accounts 及分配权限
选择排序法(C语言)
2022年深圳杯建模A题思路: 破除“尖叫效应”与“回声室效应”,走出“信息茧房”
看得见风和日丽,看不见风起“云”涌









