How to calculate n log n = c

后端 未结 2 1081
终归单人心
终归单人心 2021-02-19 20:42

I have a homework problem for my algorithms class asking me to calculate the maximum size of a problem that can be solved in a given number of operations using an O(n log n) alg

2条回答
  •  孤街浪徒
    2021-02-19 21:21

    There is no closed-form formula for this equation. Basically, you can transform the equation:

     n log n = c
    log(n^n) = c
         n^n = exp(c)
    

    Then, this equation has a solution of the form:

    n = exp(W(c))
    

    where W is Lambert W function (see especially "Example 2"). It was proved that W cannot be expressed using elementary operations.

    However, f(n)=n*log(n) is a monotonic function. You can simply use bisection (here in python):

    import math
    
    def nlogn(c):
        lower = 0.0
        upper = 10e10
        while True:
            middle = (lower+upper)/2
            if lower == middle or middle == upper:
                return middle
            if middle*math.log(middle, 2) > c:
                upper = middle
            else:
                lower = middle
    

提交回复
热议问题