Ad Code

Factorial of a Number & Trailing Zero in factorial Using Python.


Factorial of a Number & Trailing Zero in factorial Using Python 



In this tutorial, we will discuss how to find the factorial of a number using recursion and simple way. 

Also, We will discuss how to count trailing zeros in a factorial.

What is Factorial?

In mathematics, the factorial is a product of all possible integers.

Example: 

We have a digit 5. 

So, the factorial of 5
 
5 = 5*4*3*2*1 

Factorial of 5 = 120

There are many ways to find the factorial in the programming language.

 

Source Code:

  • To find factorial in a simple way using a for loop.
 num=int(input('Enter a number : ')) #get input from user
 def fact(num): #fact is a function
   fac=1 
   if num==1 or num==0:   
       return 1
   for i in range(1,(num+1)):
       fac=fac*i 
   return fac #return factorial
 print("Factorial of number: ",fact(num)) # print factorial

Output:

Enter a number: 5
Factorial of number:  120

  • To find factorial in a simple way using a while loop.
 num=int(input('enter a number : '))
 def fact(num):
    if num==0:
        return 1
    elif num==1:
        return 1
    else:
        fac=1
        while(num>1):
            fac=fac*num
            num=num-1
    return fac
 print(fact(num))

Output:

Enter a number: 5
Factorial of number:  120

  • To find factorial using recursion.
 def fact(num):
    if num==1 or num==0:
        return 1
    else:
        return num*fact(num-1)

   num=int(input("Enter a number: "))
   fac= fact(num)
   print(fac)

What is Trailing Zero in factorial?

A simple function is to first calculate the factorial of number, then count the trailing zero in the output.

Example: 

We have a digit 5, then the factorial of 5 is 120 and the trailing zero in the factorial output is only 1.

Another example, factorial of 20 is 2432902008176640000 and the trailing zero of 20 is 4.

Source Code:

 def fact(num):
    if num==1 or num==0:
        return 1
    else:
        return num*fact(num-1)

    num=int(input("Enter a number: "))

  def trailingZero(num):
    fac= fact(num)
    print(fac)
    count=0
    i=5
    while(num>=i):
        num=num//i
        count=count+num
    return count

 print("Count of trailing Zero: ",trailingZero(num))

Output:

Enter a number: 100

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Count of trailing Zero: 24

Post a Comment

0 Comments

Ad Code