Running time/time complexity for while loop with square root

前端 未结 1 1177
长发绾君心
长发绾君心 2021-01-21 03:09

This question looks relatively simple, but I can\'t seem to find the running time in terms of n.

Here is the problem:

j = n;
while(j >= 2) {
    j = j         


        
1条回答
  •  温柔的废话
    2021-01-21 03:46

    Work backwards to get the number of time units for line 2:

                                       time
    n              n       log_2(n)    units
    1              1        0          0
    2              2        1          1
    4              4        2          2
    16             16       4          3
    16^2           256      8          4
    (16^2)^2       65536    16         5
    ((16^2)^2)^2)  ...      32         6
    

    In other words, for the number of time units t, n is 2^(2^(t-1)) except for the case t = 0 in which case n = 1.

    To reverse this, you have

    t = 0 when n < 2

    t = log2(log2(n)) + 1 when n >= 2

    where log2(x) is known as the binary logarithm of x.

    0 讨论(0)
提交回复
热议问题