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 count of times p appears in the prime factors of the elements from the range [ l , r ] ; To store the required count ; Number of values in the range [ 0 , r ] that are divisible by val ; Number of values in the range [ 0 , l - 1 ] that are divisible by val ; Increment the power of the val ; ( a - b ) is the count of numbers in the range [ l , r ] that are divisible by val ; No values that are divisible by val thus exiting from the loop ; Driver code
#include <iostream> NEW_LINE using namespace std ; int getCount ( int l , int r , int p ) { int cnt = 0 ; int val = p ; while ( 1 ) { int a = r / val ; int b = ( l - 1 ) / val ; val *= p ; if ( a - b ) { cnt += ( a - b ) ; } else break ; } return cnt ; } int main ( ) { int l = 2 , r = 8 , p = 2 ; cout << getCount ( l , r , p ) ; return 0 ; }