Computer >> Computer tutorials >  >> Programming >> C programming

C program to find trailing zero in given factorial


In order to find the trailing zero in a given factorial, let us consider three examples as explained below −

Example 1

Input − 4

Output − 0

Explanation − 4! = 24, no trailing zero.

Factorial 4! = 4 x 3 x 2x 1 = 24. No trailing zero i.e. at 0’s place 4 number is there.

Example 2

Input − 6

Output − 1

Explanation − 6! = 720, one trailing zero.

Factorial 6! = 6 x 5 x 4 x 3 x 2 x 1 = 720, one trailing zero, because at 0’s place 0 number is there.

Example 3

The input is as follows −

n = 4
n = 5

The output is as follows −

No − of trailing zeroes of 4! is 0

N0 − of trailing zeroes of 5! is 1

Example

Following is the C program to find the trailing zero in a given factorial

#include <stdio.h>
static int trailing_Zeroes(int n){
   int number = 0;
   while (n > 0) {
      number += n / 5;
      n /= 5;
   }
   return number;
}
int main(void){
   int n;
   printf("enter integer1:");
   scanf("%d",&n);
   printf("\n no: of trailing zeroe's of factorial %d is %d\n\n ", n, trailing_Zeroes(n));
   printf("enter integer2:");
   scanf("%d",&n);
   printf("\n no: of trailing zeroe's of factorial %d is %d ", n, trailing_Zeroes(n));
   return 0;
}

Output

When the above program is executed, it produces the following result −

enter integer1:5
no: of trailing zeroe's of factorial 5 is 1
enter integer2:6
no: of trailing zeroe's of factorial 6 is 1