C language method to calculate the factorial of n: 1. Calculate the factorial through a for loop, code such as "for (i = 1; i <= n; i ){fact *= i;}"; 2 , calculate factorial through while loop, code such as "while (i <= fact="" int="" res="n;if" n=""> 1)res...".
The operating environment of this tutorial: Windows 7 system, c99 version, Dell G3 computer.
How to calculate the factorial of n in C language?
Find the factorial of n in C language:
About To find the factorial problem of n, let’s look at a question first and use it to find the breakthrough point.
Problem Description
Given an integer n, find its factorial, 0≤n≤ 12
Input
Input a number n
Output
Output a number representing n Factorial
Sample Input
5
Sample Output
120
Since we are looking for factorial, the breakthrough point is obvious.
The breakthrough point is : factorial
The concept and background of factorial:
1️⃣Concept:
The factorial of a positive integer (factorial ) is the product of all positive integers less than and equal to this number, and the factorial of 0 is 1. The factorial of a natural number n is written n!.
2️⃣Background:
In 1808, Christian Kramp (1760~1826) introduced this notation.
3️⃣ Calculation method of factorial:
Any natural number n greater than or equal to 1 Factorial representation method: n!=1×2 ×3×…×(n-1)×n or n!=n×(n-1)!Note: The factorial of 0 is 1, which is 0! =1. 1! = 1
2! = 2 * 1 = 2
3! = 3 * 2 * 1 = 6
…
n! = n * (n-1) *… * 2 * 1
①for loop
#include<stdio.h>int main(){ int n; scanf("%d", &n); int fact = 1; int i; for (i = 1; i <= n; i++) { fact *= i; } printf("%d\n", fact); return 0;}
5120--------------------------------Process exited after 1.475 seconds with return value 0请按任意键继续. . .
②while loop
#include<stdio.h>int main(){ int n; scanf("%d", &n); int fact = 1; int i = 1; while (i <= n) { fact *= i; i++; } printf("%d\n", fact); return 0;}
6720--------------------------------Process exited after 1.549 seconds with return value 0请按任意键继续. . .
1️⃣Writing method one
#include <stdio.h>int Fact(int n);int main() //主函数{ int n, cnt; scanf("%d", &n); cnt = Fact(n); printf("%d\n", cnt); return 0;} int Fact(int n) //递归函数 { int res = n; if (n > 1) res = res * Fact(n - 1); return res;}
7 * 6 * 5 * 4 * 3 * 2 * 1
= 1 * 2 * 3 * 4 * 5 * 6 * 7
= 5040
75040--------------------------------Process exited after 2.563 seconds with return value 0请按任意键继续. . .
2️⃣Writing method two
#include <stdio.h>int Fact(int n) //递归函数 { int res = n; if (n > 1) res = res * Fact(n - 1); return res;}int main() //主函数 { int n, cnt; scanf("%d", &n); cnt = Fact(n); printf("%d\n", cnt); return 0;}
= 1 * 2 * 3 * 4 * 5 * 6
= 720
6720--------------------------------Process exited after 1.829 seconds with return value 0请按任意键继续. . .
C language video tutorial]
The above is the detailed content of How to calculate the factorial of n in C language. For more information, please follow other related articles on the PHP Chinese website!