一个数的阶乘的Python程序
非负整数的阶乘,是所有小于或等于 n 的整数的乘积。例如,6 的阶乘是 6*5*4*3*2*1,即 720。
1.递归:
python3
# Python 3 program to find
# factorial of given number
def factorial(n):
# single line to find factorial
return 1 if (n==1 or n==0) else n * factorial(n - 1);
# Driver Code
num = 5;
print("Factorial of",num,"is",
factorial(num))
# This code is contributed by Smitha Dinesh Semwal
python3
# Python 3 program to find
# factorial of given number
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
# Driver Code
num = 5;
print("Factorial of",num,"is",
factorial(num))
# This code is contributed by Dharmik Thakkar
Python3
# Python 3 program to find
# factorial of given number
def factorial(n):
# single line to find factorial
return 1 if (n==1 or n==0) else n * factorial(n - 1)
# Driver Code
num = 5
print ("Factorial of",num,"is",
factorial(num))
# This code is contributed
# by Smitha Dinesh Semwal.
Python3
# Python 3 program to find
# factorial of given number
import math
def factorial(n):
return(math.factorial(n))
# Driver Code
num = 5
print("Factorial of", num, "is",
factorial(num))
# This code is contributed by Ashutosh Pandit
输出:
Factorial of 5 is 120
2. 迭代:
蟒蛇3
# Python 3 program to find
# factorial of given number
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
# Driver Code
num = 5;
print("Factorial of",num,"is",
factorial(num))
# This code is contributed by Dharmik Thakkar
输出:
Factorial of 5 is 120
3.一条线解决方案(使用三元运算符):
Python3
# Python 3 program to find
# factorial of given number
def factorial(n):
# single line to find factorial
return 1 if (n==1 or n==0) else n * factorial(n - 1)
# Driver Code
num = 5
print ("Factorial of",num,"is",
factorial(num))
# This code is contributed
# by Smitha Dinesh Semwal.
输出:
Factorial of 5 is 120
有关更多详细信息,请参阅有关数字阶乘的完整文章!
4.通过使用内置函数:
Python3
# Python 3 program to find
# factorial of given number
import math
def factorial(n):
return(math.factorial(n))
# Driver Code
num = 5
print("Factorial of", num, "is",
factorial(num))
# This code is contributed by Ashutosh Pandit
输出:
Factorial of 5 is 120