Count occurrences of a prime number in the prime factorization of every element from the given range | Function to return the highest power of p that divides n ; Function to return the count of times p appears in the prime factors of the elements from the range [ l , r ] ; To store the required count ; For every element of the range ; Add the highest power of p that divides i ; Driver code
function countFactors ( n , p ) { let pwr = 0 ; while ( n > 0 && n % p == 0 ) { n /= p ; pwr ++ ; } return pwr ; } function getCount ( l , r , p ) { let cnt = 0 ; for ( let i = l ; i <= r ; i ++ ) { cnt += countFactors ( i , p ) ; } return cnt ; } let l = 2 , r = 8 , p = 2 ; document . write ( getCount ( l , r , p ) ) ;