Count number of trailing zeros in ( 1 ^ 1 ) * ( 2 ^ 2 ) * ( 3 ^ 3 ) * ( 4 ^ 4 ) * . . | 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
< ? php function trailing_zeros ( $ N ) { $ count_of_two = 0 ; $ count_of_five = 0 ; for ( $ i = 1 ; $ i <= $ N ; $ i ++ ) { $ 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 ; } } $ ans = min ( $ count_of_two , $ count_of_five ) ; return $ ans ; } $ N = 12 ; echo trailing_zeros ( $ N ) ; ? >