Find numbers with K odd divisors in a given range | Java program to count numbers with k odd divisors in a range . ; Utility function to check if number is perfect square or not ; Utility Function to return count of divisors of a number ; Note that this loop runs till square root ; If divisors are equal , count it only once ; Otherwise print both ; Function to calculate all divisors having exactly k divisors between a and b ; Initialize result ; calculate only for perfect square numbers ; check if number is perfect square or not ; total divisors of number equals to k or not ; Driver program to run the case
import java . io . * ; import java . math . * ; class GFG { static boolean isPerfect ( int n ) { int s = ( int ) ( Math . sqrt ( n ) ) ; return ( s * s == n ) ; } static int divisorsCount ( int n ) { int count = 0 ; for ( int i = 1 ; i <= Math . sqrt ( n ) + 1 ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) count += 1 ; else count += 2 ; } } return count ; } static int kDivisors ( int a , int b , int k ) { int count = 0 ; for ( int i = a ; i <= b ; i ++ ) { if ( isPerfect ( i ) ) if ( divisorsCount ( i ) == k ) count ++ ; } return count ; } public static void main ( String args [ ] ) { int a = 21 , b = 149 , k = 333 ; System . out . println ( kDivisors ( a , b , k ) ) ; } }