Challenge: The Nearest Power of 2
Find the nearest power of 2 for a number that has been input.
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, and are both the powers of nearest to . The function should display because it’s smaller than .
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
is50
and thepwr
is64
, 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, ifnum
is50
, then the output on the console should beThe 64 is the power of 2 nearest to 50.
.
# 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.