What is the time complexity of the following function?

后端 未结 3 1713
走了就别回头了
走了就别回头了 2020-12-17 04:00
    int func(int n){
       if(n==1)
         return 0;
       else
         return sqrt(n);
    }

Where sqrt(n) is a C math.h library function.

3条回答
  •  Happy的楠姐
    2020-12-17 04:40

    I am going to give a bit more general case answer, without assuming constant size of int.

    The answer is Theta(logn).

    We know newton-raphson is Theta(logn) - that excludes Theta(n) (assuming sqrt() is as efficient as we can).

    However, a general number n requries log_2(n) bits to encode - and you require to read all of it in order to get an accurate sqrt() function. This excludes Theta(1) and Theta(log(log(n)).

    From the above, we know that the complexity of the function is Theta(log(n)).

    As a side note, since O(log(n)) is a subset of O(n) - it is also a valid answer, though not tight one. For more information about big Theta and big O and their differences, you might want to have a look on this thread.

提交回复
热议问题