Challenge: The Nearest Power of 2

Task

Write a program that takes a positive number (num) and finds the power of 2 nearest to that number. The program stores the resulting value to pwr.

If there are two candidate values, display the smaller one. For example, 22 and 44 are both the powers of 22 nearest to 33. The function should display 22 because it’s smaller than 44.


Sample input 1

test_value = 40

The resulting value 1

pwr = 32

Expected output 1

The 32 is the power of 2 nearest to 40.

Sample input 2

test_value = 50

The resulting value 2

pwr = 64

Expected output 2

The 64 is the power of 2 nearest to 50.

How to test your program

When you click the “Test” button under the code widget, you’ll get the two options explained below:

  • Show Results: It shows the sample inputs and their respective results in comparison with the expected output. The actual output is the power calculated to display the results. The word “Succeeded” in the last column indicates that the calculated output matches the expected output. For example, if num is 50 and the pwr is 64, then the last column shows “Succeeded”.

  • Show Console: It shows the output from the print() statements used in your code. You can use this to verify your calculations on the basis of sample test inputs. For example, if num is 50, then the output on the console should be The 64 is the power of 2 nearest to 50..

Press + to interact
# Assume that the variable test_value is already defined.
num = test_value # The variable test_value contains the value to be tested.
pwr = 0 # The variable to store the result calculated with the help of num.
# You are required to calculate the value of pwr as
# the power of 2 nearest to the num.
# You may start your code from here onwards.