Check if ceil of number divided by power of two exist in sorted array | Function to find there exist a number or not in the array ; Loop to check if there exist a number by divided by power of 2 ; Binary Search ; Condition to check the number is found in the array or not ; Otherwise divide the number by increasing the one more power of 2 ; Driver Code
function findNumberDivByPowerofTwo ( ar , k , n ) { var found = - 1 , m = k ; while ( m > 0 ) { var l = 0 ; var r = n - 1 ; while ( l <= r ) { var mid = parseInt ( ( l + r ) / 2 ) ; if ( ar [ mid ] == m ) { found = m ; break ; } else if ( ar [ mid ] > m ) { r = mid - 1 ; } else if ( ar [ mid ] < m ) { l = mid + 1 ; } } if ( found != - 1 ) { break ; } m = parseInt ( m / 2 ) ; } return found ; } var arr = [ 3 , 5 , 7 , 8 , 10 ] ; var k = 4 , n = 5 ; document . write ( findNumberDivByPowerofTwo ( arr , k , n ) ) ;