简体   繁体   English

成本计算和寻找大 O 符号

[英]Cost calculation and finding the big O notaion

When calculating the cost to identify the Big O notation of this code, should I count following line too?在计算识别此代码的大 O 表示法的成本时,我是否也应该计算以下行?

if(n == 0): print("Incorrect index No ") if(n == 0): print("不正确的索引号")

if yes how to connect it with the loop如果是,如何将其与循环连接

def FindFibonacci(n):
    

    if(n == 0):
        print("Incorrect index No ")
        
           
    else:
        
        n1 = 0
        n2 = 1
        x = 0
        while (x<n):
            print(n1)
            fib = n1 + n2
            n1 = n2
            n2 = fib

            x = x+1
            
num = int(input("How many Fibonacci sequences you want? "))  

FindFibonacci(num)

Yes, when calculating the cost to identify the Big O notation of this code, you should also take the following line into account:是的,在计算识别此代码的大 O 表示法的成本时,您还应该考虑以下行:

if(n == 0):
    print("Incorrect index No ")

It is not customary to include print statements in a function of which you want to identify the time complexity, but since the output string has a constant number of characters, we may assume it executes in O(1).不习惯在要确定时间复杂度的 function 中包含print语句,但由于 output 字符串具有恒定数量的字符,我们可以假设它在 O(1) 中执行。

how to connect it with the loop?如何将它与循环连接?

The evaluation of the if condition ( n == 0 ) has O(1) time complexity. if条件 ( n == 0 ) 的评估具有 O(1) 时间复杂度。 When that condition is true, the print statement adds O(1) time complexity and the loop is not executed.当该条件为真时, print语句会增加 O(1) 时间复杂度,并且不会执行循环。 So the overall time complexity for that particular case is O(1 + 1) = O(1).因此,该特定情况的总体时间复杂度为 O(1 + 1) = O(1)。

For the case where the if condition is not true, the loop gets executed, so you need to find out what the loop's time complexity is.对于if条件不成立的情况,循环被执行,所以你需要找出循环的时间复杂度是多少。 You'll find it is O(n).你会发现它是 O(n)。 So in total you have O(1 + n) which still is O(n).所以总的来说你有 O(1 + n) 仍然是 O(n)。

Taking all cases together -- including where n is 0 -- we get O(1 + n) which is O(n).将所有情况放在一起——包括 n 为 0 的情况——我们得到 O(1 + n),即 O(n)。

Let us recall that让我们回忆一下

f(n) = O(g(n)) if there are constants c and N such that for all n≥N , |f(n)|≤g(n) . f(n) = O(g(n))如果存在常数cN使得对于所有n≥N|f(n)|≤g(n)

So one can safely ignore all special cases arising below some bounded value, and here the case of n=0 is quite irrelevant (you don't even evaluate its cost).所以人们可以放心地忽略所有低于某个有界值的特殊情况,这里n=0的情况是完全不相关的(你甚至不评估它的成本)。

Other example:其他示例:

if n < 1000 then print(n!) else print('Overflow')

has complexity O(1) .复杂度O(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM