Noah Santos
Noah Santos

Reputation: 143

A function that takes x and returns the largest power of 2 less than or equal to the number

I am trying to make a program that takes a positive number and returns it with the largest power of 2 less than or equal to that number.

For example,

pow2(12)->8

I am having trouble with my code:

 import math
import random

def pow2(n):
    return 2**int(math.log(n,2))

pow2(12)

Is my code doing what its suppose to do? Why isn't it returning a number?

Upvotes: 1

Views: 1776

Answers (1)

vash_the_stampede
vash_the_stampede

Reputation: 4606

The issue is with not assigning the return value to a variable

import math
import random

def pow2(n):
    return 2**int(math.log(n,2))

x = pow2(12) # here
print(x)

Alternatively you could

print(pow2(12))

Upvotes: 2

Related Questions