Skip to content
Related Articles

Related Articles

Golang Program to Count Trailing Zeros in Factorial of a Number
  • Last Updated : 12 May, 2020
GeeksforGeeks - Summer Carnival Banner

Given an integer n, write a Go program to count the number of trailing zeros in the factorial of n.

Examples:

Input : 7
Output : 1
Explanation: 7! = 5040, which has 1 trailing zero

Input : 10
Output : 2
Explanation: 10! = 3628800, which has 2 trailing zeros

Naive approach: To count the trailing zeros in n!, one approach is to find the factorial of n and then count the number of trailing zeros using a loop and counting the number of (n%10==0)s. However, even for small numbers such as 20, the factorial value is large enough to cause integer overflow.

Efficient Approach: To count the number of trailing zeros, it is first required to understand what contributes trailing zeros in the factorial of a number.

The number 10 is responsible for the trailing zeros. The prime factorization of 10 is 2*5. In prime factorization of any number, the number of 2s is always greater than or equal to the number of 5s. Hence, it is only required to find the number of fives in the prime factorization of the number.



Example 1: When n = 7, the prime factorization of 7! is 2^4 * 3^2 * 5^1 * 7^1. The number of 5s in the prime factorization is 1. Hence, the number of trailing zeros in 7! is 1.

Example 2: When n = 10, the prime factorization of 10! is 2^8 * 3^4 * 5^2 * 7^1. The number of 5s in the prime factorization is 2. Hence, the number of trailing zeros in 10! is 2.

trailingZerosCount = floor(n/5) + floor(n/5^2) + floor(n/5^3) + …. + floor(n/5^k) where 5^k <= n




// Golang Program to Count Trailing
// Zeros in Factorial of a Number
package main
  
import (
    "fmt"
)
  
func trailingZeros(n int) int {
  
    // This function return the number of
    // trailing zeros in the factorial of
    // a number n.
    // The count variable denotes the
    //  number of trailing zeros in n!
    count := 0
      
    // This loop counts the number 
    // of occurrences of 5 and its
    // powers in n!
    // Starting with p = 5, the loop
    // calculates floor(n/5) + floor(n/25) + 
    // floor(n/125) + ..... until n/p >0
    for p := 5; n/p > 0; p *= 5 {
        count += n / p
    }
    return count
}
  
// Driver code
func main() {
    n := 10
    fmt.Printf("The number of trailing zeros"+
         " in %v! is %v", n, trailingZeros(n))
}

Output:

The number of trailing zeros in 10! is 2

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :