Count number of trailing zeros in ( 1 ^ 1 ) * ( 2 ^ 2 ) * ( 3 ^ 3 ) * ( 4 ^ 4 ) * . . | Java implementation of the approach ; Function to return the number of trailing zeros ; To store the number of 2 s and 5 s ; If we get a factor 2 then we have i number of 2 s because the power of the number is raised to i ; If we get a factor 5 then we have i number of 5 s because the power of the number is raised to i ; Take the minimum of them ; Driver code
class GFG { static int trailing_zeros ( int N ) { int count_of_two = 0 , count_of_five = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { int val = i ; while ( val % 2 == 0 && val > 0 ) { val /= 2 ; count_of_two += i ; } while ( val % 5 == 0 && val > 0 ) { val /= 5 ; count_of_five += i ; } } int ans = Math . min ( count_of_two , count_of_five ) ; return ans ; } public static void main ( String [ ] args ) { int N = 12 ; System . out . println ( trailing_zeros ( N ) ) ; } }