Program to find the Nth natural number with exactly two bits set | Set 2 | Function to find the Nth number with exactly two bits set ; Initialize variables ; Initialize the range in which the value of ' a ' is present ; Perform Binary Search ; Find the mid value ; Update the range using the mid value t ; Find b value using a and N ; Print the value 2 ^ a + 2 ^ b ; Driver Code ; Function Call
def findNthNum ( N ) : NEW_LINE INDENT last_num = 0 NEW_LINE left = 1 NEW_LINE right = N NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = left + ( right - left ) // 2 NEW_LINE t = ( mid * ( mid + 1 ) ) // 2 NEW_LINE if ( t < N ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT elif ( t == N ) : NEW_LINE INDENT a = mid NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT a = mid NEW_LINE right = mid - 1 NEW_LINE DEDENT DEDENT t = a - 1 NEW_LINE b = N - ( t * ( t + 1 ) ) // 2 - 1 NEW_LINE print ( ( 1 << a ) + ( 1 << b ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 15 NEW_LINE findNthNum ( N ) NEW_LINE DEDENT