Golang Program to Count Trailing Zeros in Factorial of a Number
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.
Go
package main import "fmt" // countZeros function counts the number of trailing zeros in the factorial of n using a naive approach func countZeros(n int) int { count := 0 for i := 1 ; i <= n; i++ { j := i for j% 5 == 0 { count++ j /= 5 } } return count } func main() { n := 10 fmt.Printf( "Count of trailing 0s in %d! is %d\n" , n, countZeros(n)) } |
Output :
Count of trailing 0s in 10! is 2
Time Complexity : O(n^2)
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
Go
// 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
Time complexity: O(log n) since for loops will run for logn times
Auxiliary Space: O(1) because it is using constant space
Please Login to comment...