Number of trailing zeroes in base B representation of N ! | To find the power of a prime p in factorial N ; calculating floor ( n / r ) and adding to the count ; increasing the power of p from 1 to 2 to 3 and so on ; returns all the prime factors of k ; vector to store all the prime factors along with their number of occurrence in factorization of B ; Returns largest power of B that divides N ! ; calculating minimum power of all the prime factors of B ; Driver code
function findPowerOfP ( N , p ) { var count = 0 ; var r = p ; while ( r <= N ) { count += ( N / r ) ; r = r * p ; } return count ; } function primeFactorsofB ( B ) { var ans = [ ] ; for ( var i = 2 ; B != 1 ; i ++ ) { if ( B % i == 0 ) { var count = 0 ; while ( B % i == 0 ) { B = B / i ; count ++ ; } ans . push ( [ i , count ] ) ; } } return ans ; } function largestPowerOfB ( N , B ) { var vec = [ ] ; vec = primeFactorsofB ( B ) ; var ans = Number . MAX_VALUE ; for ( var i = 0 ; i < vec . length ; i ++ ) ans = Math . min ( ans , Math . floor ( findPowerOfP ( N , vec [ i ] [ 0 ] ) / vec [ i ] [ 1 ] ) ) ; return ans ; } document . write ( largestPowerOfB ( 5 , 2 ) + " " ) ; document . write ( largestPowerOfB ( 6 , 9 ) + " " ) ;