Check if ceil of number divided by power of two exist in sorted array | C ++ 14 implementation to check if a number divided by power of two exist in the 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumberDivByPowerofTwo ( int ar [ ] , int k , int n ) { int found = -1 , m = k ; while ( m > 0 ) { int l = 0 ; int r = n - 1 ; while ( l <= r ) { int mid = ( 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 = m / 2 ; } return found ; } int main ( ) { int arr [ ] = { 3 , 5 , 7 , 8 , 10 } ; int k = 4 , n = 5 ; cout << findNumberDivByPowerofTwo ( arr , k , n ) ; }