Highest Power

‘’’

Python3 program to find highest power of 2 smaller

than or equal to n.

import sys

def highestPowerof2( n):

# Invalid input 
if (n < 1): 
	return 0

res = 1

#Try all powers starting from 2^1 
for i in range(8*sys.getsizeof(n)): 

	curr = 1 << i 

	# If current power is more than n, break 
	if (curr > n): 
		break

	res = curr 

return res 

Driver code

if name == “main”:

n = 10
print(highestPowerof2(n)) 

Could anyone tell me how this code works. What is this sys library?
Also Please add how the code appears like this on posting though the original code was different.

import math

def highestPowerof2(n):

p = int (math.log(n, 2 ));

return int ( pow ( 2 , p));

# Driver code

n = 10 ;

print (highestPowerof2(n));

This is a way you can use
Please like the post

2 Likes

why do you need it to be this complex? the solution is simple enough

I was looking on the net how to do in c++ when I came across this. I am new to C++ so I am not able to understand it.

u want code ? or something else?

int highest(int n){
if(n<1) return 0;
int i=0;
while(1){
     x = 1<<i;
     if(x==n) 
         return(x);
     else if(x>n) 
         return(1<<(i-1));
     i++;
     }
}