Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to compute floor of log(n,b) for integers n and b?

Tags:

python

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?

like image 423
jodag Avatar asked Feb 10 '18 21:02

jodag


People also ask

Is the floor function discontinuous at every integer?

The floor function is discontinuous at every integer. [1] \lfloor x floor \le x < \lfloor x floor +1 ⌊x⌋ ≤ x < ⌊x⌋+1 is often enough to solve basic problems involving the floor function. ⌊ 0.5 + ⌊ x ⌋ ⌋ = 20.

How do you find the floor function of a given interval?

If your answer is in the form a + b. a+b. a+b. \lfloor \cdot floor ⌊⋅⌋ denotes the floor function. Definite integrals and sums involving the floor function are quite common in problems and applications. The best strategy is to break up the interval of integration (or summation) into pieces on which the floor function is constant.

How to calculate log to the base 10 in Java?

Math class in Java (java.lang.Math) is a library which holds the functions to calculate such values, like sin (), cos (), log () etc. But the log () method in Math class calculates the log to the base 10.

Can you omit multiplying by a constant in log base 2?

If you're taking a log base 2 of a binary number, you can even omit the multiplying by a constant, making it . Could anyone give a casual explanation of the difference between complexity classes and time complexity classes, and the differing need (s) each was conceived to address?


Video Answer


1 Answers

One way is to make your function self-correcting:

def floor_log(n,b):
    res = math.floor(math.log(n,b))
    return res + 1 if b**(res+1) == n else res 

Or a bit more obscure:

def floor_log(n,b):
    res = math.floor(math.log(n,b))
    return res + (b**(res+1) == n) 
like image 145
trincot Avatar answered Nov 10 '22 04:11

trincot