Write a program in Python to calculate the factorial value of a number
When we talk about factorial of a number , then the factorial of that number can be represented in the following manner :
n! = n * (n-1) * (n-2) * (n-3)
So , if one wants to calculate the factorial of a number using a logical code construct , then one may write the same using a decremental loop and the loop iteration would work till the value of the loop iterator reaches the value of '1' and in each of the step of iteration , the cumulative value of the product of the number with a number decremented by 1 at each of the step is multiplied with each other at each of the steps .
Let this be represented in the following manner :
product = 1
while n >= 1:
product = product * n
n = (n-1)
Here , first the value of product is initialized to 1 which is the cumulative product of the values is multiplied at each of the step iterated over a while loop and then product of the cumulative end result is published at product of the cumulative end result is published at the end when value of n happens tobe either 1 or greater than or equal to 1 which self deprecates to the value of 1 by reducing the value of n by 1 in each of the steps till the while loop evaluates to the condition true in each of the looping iterations at each of the steps within the while loop The program for the above evaluation can be given in the following manner :
def fact(n):
""" find the factorial value """
product = 1
while n >= 1:
product = product * n
n = n - 1
return product
""" display the factorials of first 10 numbers call fact() function and pass the numbers from 1 to
10 within the fact function as a parameter """
for i in range(1,11):
print(' Factorial of {} is {}'.format(i,fact(i)))
Output
======
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Factorial of 6 is 720
Factorial of 7 is 5040
Factorial of 8 is 40320
Factorial of 9 is 362880
Factorial of 10 is 3628800
No comments:
Post a Comment