Count occurrences of a prime number in the prime factorization of every element from the given range | Java 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
import java . util . * ; class GFG { static int getCount ( int l , int r , int p ) { int cnt = 0 ; int val = p ; while ( true ) { int a = r / val ; int b = ( l - 1 ) / val ; val *= p ; if ( ( a - b ) > 0 ) { cnt += ( a - b ) ; } else break ; } return cnt ; } public static void main ( String [ ] args ) { int l = 2 , r = 8 , p = 2 ; System . out . println ( getCount ( l , r , p ) ) ; } }