python编程求n的阶乘_使⽤Python编程的阶乘
python编程求n的阶乘
Before we start implementing factorial using Python, let us first discuss what factorial of a number implies.
在开始使⽤Python实现阶乘之前,让我们⾸先讨论数字阶乘的含义。
Theoretically, the factorial of a number is defined as the product of all positive integers less than or equal to the number. Certainly, ‘n!’ represents the factorial of an integer ‘n’. As an example, let us look at the factorial of the number 6,
从理论上讲,数字的阶乘定义为所有⼩于或等于该数字的正整数的乘积。 当然, “ n!” 代表整数'n'的阶乘。 例如,让我们看⼀下数字6的阶乘
6! = 6 * 5 * 4 * 3 * 2 * 1
6! = 6 * 5 * 4 * 3 * 2 * 1
The following techniques could be followed to determine the factorial of an integer.
可以遵循以下技术确定整数的阶乘。
1. Using Loop
使⽤循环
2. Using Recursive function call
使⽤递归函数调⽤
3. Using predefined function ‘factorial()’ from the math module
使⽤数学模块中的预定义函数'factorial()'
在Python中使⽤循环 (Using Loop in Python)
The below-mentioned code illustrates how we can calculate the factorial of a given number using for loop in Python programming.
下⾯提到的代码说明了如何在Python编程中使⽤for 循环来计算给定数字的阶乘。
n=9
fact=1
for i in range(2,n+1):
fact=fact*i
print("The factorial of ",n," is: ",fact)
Output:
输出:
The factorial of 9 is: 362880
在Python中使⽤递归函数调⽤ (Using Recursion function call in Python)
Similarly, we can also calculate the factorial of a given number using a Recursive function. Let us see how
同样,我们也可以使⽤递归函数来计算给定数字的阶乘。 让我们看看
n=9
def fact(n):
if(n==1 or n==0):
return 1
else:
return n*fact(n-1)
print("The factorial of ",n," is: ",fact(n))
Output
输出量
The factorial of 9 is: 362880
For a clear understanding of functions and recursion, one can refer to
为了清楚地了解函数和递归 ,可以参考
在Python中使⽤Math模块中的factorial()⽅法 (Using the factorial() method from the math module in Python)
The math module provides a simple way to calculate the factorial of any positive integer. Certainly, the module comes with a pre-defined method ‘factorial()’ which takes in the integer as an argument and returns the factorial of the number. Let’s take a look at how we can use the pre-defined method and consequently find the factorial. The code given below depicts how the method ‘factorial()‘ can be used
数学模块提供了⼀种简单的⽅法来计算任何正整数的阶乘。 当然,该模块带有预定义的⽅法'factorial()' ,该⽅法将整数作为参数并返回数字的阶乘。 让我们看⼀下如何使⽤预定义⽅法并因此到阶乘。 下⾯给出的代码描述了如何使⽤⽅法' factorial() '
c语言用递归函数求n的阶乘import math
n=9
print("The factorial of ",n," is: ",math.factorial(n))
Output:
输出:
The factorial of 9 is: 362880
Furthermore, in the case of all of the above-mentioned techniques, we have used a pre-defined value of the integer ‘n’. Also making ‘n’ a user input is possible. This could be easily achieved by substituting the line ‘n=9’ with:
此外,在所有上述技术的情况下,我们使⽤了整数“ n”的预定义值。 也可以使⽤户输⼊为“ n” 。 通过将⾏“ n = 9”替换为:
n=int(input("Enter the number for calculating factorial"))
The is covered in further detail in one of our previous articles.我们之前的⼀篇⽂章进⼀步详细介绍了 。
References:
参考⽂献:
python编程求n的阶乘
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论