Method 1: recursive method
Recursive method is a common method to calculate factorial, which is solved by splitting the problem into smaller subproblems. Specifically, the calculation formula of recursive method is:
n! =n×(n- 1)!
Where, n! Represents the factorial of n. According to this formula, we can write recursive functions to calculate the factorial of positive integers. The following is an example of Python code that uses recursive method to calculate factorial:
```
deffactorial(n):
ifn== 1:
return 1
Otherwise:
Factorial of returnn * (n- 1)
```
In this code, when n is equal to 1, the function returns 1, otherwise the function returns the factorial of n times n- 1. The advantage of calculating factorial by recursive method is that the code is easy to understand, but for large numbers, the depth of recursion will be very large, which may lead to stack overflow.
Method 2: Cycle method
Cyclic method is another method to calculate factorial, and the result is calculated by iterative loop. Specifically, the calculation formula of the cyclic method is:
n! = 1×2×3×...×n
According to this formula, we can use cyclic iteration to calculate the factorial of positive integers. The following is an example of Python code for calculating factorial by loop method:
```
deffactorial(n):
Result = 1
foriinrange( 1,n+ 1):
Result *=i
Return results
```
In this code, we use the for loop to iteratively calculate the factorial of n. The advantage of the loop method is that it is fast, but for large numbers, it may lead to integer overflow.
Method 3: Stirling formula
Sterling formula is an approximate method to calculate factorial, and the result is calculated by approximate logarithm of factorial. Specifically, the Stirling formula is as follows:
n! =sqrt(2πn)×(n/e)^n
Where e is the base of natural logarithm, which is approximately equal to 2.7 1828. The advantage of calculating factorial with Stirling formula is that it is fast and accurate for large numbers. The following is an example of Python code that uses Stirling formula to calculate factorial:
```
Import mathematics
deffactorial(n):
return math . sqrt(2 * math . pi * n)*(n/math . e)* * n
```
In this code, we use sqrt and E functions in the math library to calculate the value of Stirling formula. It should be noted that the Stirling formula is only an approximate calculation, which may not be applicable to some problems that need accurate calculation.