K | Java program to find k - th term of N merged Arithmetic Progressions ; Function to count and return the number of values less than equal to N present in the set ; Check whether j - th bit is set bit or not ; Function to implement Binary Search to find K - th element ; Find middle index of the array ; Search in the left half ; Search in the right half ; If exactly K elements are present ; Driver Code
import java . util . * ; class GFG { static final int maxm = 1000000000 ; static int count ( int [ ] v , int n ) { int i , odd = 0 , even = 0 ; int j , d , count ; int t = ( int ) 1 << v . length ; int size = v . length ; for ( i = 1 ; i < t ; i ++ ) { d = 1 ; count = 0 ; for ( j = 0 ; j < size ; j ++ ) { if ( ( i & ( 1 << j ) ) > 0 ) { d *= v [ j ] ; count ++ ; } } if ( count % 2 == 1 ) odd += n / d ; else even += n / d ; } return ( odd - even ) ; } static int BinarySearch ( int l , int r , int [ ] v , int key ) { int mid ; while ( r - l > 1 ) { mid = ( l + r ) / 2 ; if ( key <= count ( v , mid ) ) { r = mid ; } else { l = mid ; } } if ( key == count ( v , l ) ) return l ; else return r ; } public static void main ( String [ ] args ) { int N = 2 , K = 10 ; int [ ] v = { 2 , 3 } ; System . out . print ( BinarySearch ( 1 , maxm , v , K ) + "NEW_LINE"); } }