Count occurrences of a prime number in the prime factorization of every element from the given range | C ++ implementation of the approach ; 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
#include <iostream> NEW_LINE using namespace std ; int countFactors ( int n , int p ) { int pwr = 0 ; while ( n > 0 && n % p == 0 ) { n /= p ; pwr ++ ; } return pwr ; } int getCount ( int l , int r , int p ) { int cnt = 0 ; for ( int i = l ; i <= r ; i ++ ) { cnt += countFactors ( i , p ) ; } return cnt ; } int main ( ) { int l = 2 , r = 8 , p = 2 ; cout << getCount ( l , r , p ) ; return 0 ; }