logo

Programa Python para encontrar el factorial de un número

¿Qué es factorial?

Factorial es un número entero no negativo. Es el producto de todos los números enteros positivos menores o iguales a ese número que pides factorial. Se indica con un signo de exclamación (!).

Ejemplo:

colecciones java
 n! = n* (n-1) * (n-2) *........1 4! = 4x3x2x1 = 24 

El valor factorial de 4 es 24.

Nota: El valor factorial de 0 es 1 siempre. (violación de la regla)

Ejemplo -

 num = int(input(&apos;Enter a number: &apos;)) factorial = 1 if num <0: 0 print(' factorial does not exist for negative numbers') elif num="=" 0: print('the of is 1') else: i in range(1,num + 1): of',num,'is',factorial) < pre> <p> <strong>Output:</strong> </p> <pre> Enter a number: 10 The factorial of 10 is 3628800 </pre> <p> <strong>Explanation -</strong> </p> <p>In the above example, we have declared a <strong>num</strong> variable that takes an integer as an input from the user. We declared a variable factorial and assigned 1. Then, we checked if the user enters the number less than one, then it returns the factorial does not exist for a negative number. If it returns false, then we check num is equal to zero, it returns false the control transfers to the else statement and prints the factorial of a given number.</p> <h3>Using Recursion</h3> <p>Python recursion is a method which calls itself. Let&apos;s understand the following example.</p> <p> <strong>Example -</strong> </p> <pre> # Python 3 program to find # factorial of given number def fact(n): return 1 if (n==1 or n==0) else n * fact(n - 1); num = 5 print(&apos;Factorial of&apos;,num,&apos;is&apos;,) fact(num)) </pre> <p> <strong>Output:</strong> </p> <pre> Factorial of 5 is 120 </pre> <p> <strong>Explanation -</strong> </p> <p>In the above code, we have used the recursion to find the factorial of a given number. We have defined the <strong>fact(num)</strong> function, which returns one if the entered value is 1 or 0 otherwise until we get the factorial of a given number.</p> <h3>Using built-in function</h3> <p>We will use the math module, which provides the built-in <strong>factorial()</strong> method. Let&apos;s understand the following example.</p> <p> <strong>Example -</strong> </p> <pre> # Python program to find # factorial of given number import math def fact(n): return(math.factorial(n)) num = int(input(&apos;Enter the number:&apos;)) f = fact(num) print(&apos;Factorial of&apos;, num, &apos;is&apos;, f) </pre> <p> <strong>Output:</strong> </p> <pre> Enter the number: 6 Factorial of 6 is 720 </pre> <p>We have imported the math module that has <strong>factorial()</strong> function. It takes an integer number to calculate the factorial. We don&apos;t need to use logic.</p> <hr></0:>

Explicación -

En el ejemplo anterior, hemos declarado un en uno Variable que toma un número entero como entrada del usuario. Declaramos una variable factorial y le asignamos 1. Luego, verificamos si el usuario ingresa el número menor que uno, luego devuelve que el factorial no existe para un número negativo. Si devuelve falso, entonces verificamos que num sea igual a cero, devuelve falso, el control se transfiere a la declaración else e imprime el factorial de un número dado.

Usando recursividad

La recursividad de Python es un método que se llama a sí mismo. Entendamos el siguiente ejemplo.

¿Qué es el mapa de Java?

Ejemplo -

 # Python 3 program to find # factorial of given number def fact(n): return 1 if (n==1 or n==0) else n * fact(n - 1); num = 5 print(&apos;Factorial of&apos;,num,&apos;is&apos;,) fact(num)) 

Producción:

 Factorial of 5 is 120 

Explicación -

En el código anterior, hemos utilizado la recursividad para encontrar el factorial de un número determinado. Hemos definido el hecho función, que devuelve uno si el valor ingresado es 1 o 0 en caso contrario hasta que obtengamos el factorial de un número determinado.

cómo saber el tamaño de la pantalla

Usando la función incorporada

Usaremos el módulo matemático, que proporciona el módulo integrado factorial() método. Entendamos el siguiente ejemplo.

Ejemplo -

 # Python program to find # factorial of given number import math def fact(n): return(math.factorial(n)) num = int(input(&apos;Enter the number:&apos;)) f = fact(num) print(&apos;Factorial of&apos;, num, &apos;is&apos;, f) 

Producción:

 Enter the number: 6 Factorial of 6 is 720 

Hemos importado el módulo de matemáticas que tiene factorial() función. Se necesita un número entero para calcular el factorial. No necesitamos usar la lógica.

cadena.contiene java