I'm looking to compute floor(log(n,b))
where n
and b
are both integers. Directly implementing this function fails for even slightly large values of n
and b
# direct implementation
def floor_log(n,b):
return math.floor(math.log(n,b))
For example, floor_log(100**3, 100)
evaluates to 2
instead of the correct value 3
.
I was able to come up with a working function which repeatedly divides until nothing remains
# loop based implementation
def floor_log(n,b):
val = 0
n = n // b
while n > 0:
val += 1
n = n // b
return val
is there a faster or more elegant way of obtaining this solution? Perhaps using built-in functionality?