![](/img/trans.png)
[英]Are these Big-O notations correct for simple loop functions (Python)?
[英]Are these Big-O notations correct for simple modulus and power functions (Python)?
假設我們有以下函數:
def modulo(a, b):
"""Take numbers a and b and compute a % b."""
if b <= 0:
return None
div = int(a / b)
return a - div*b
def power(a, b):
"""Take number a and non-negative integer b.
Compute a**b."""
if b == 0:
return 1
else:
return a * power(a, b - 1)
對於modulo
,是大 O 符號O(a / b)
嗎? 因為執行所需的時間取決於 a 和 b 輸入。 但是,我在網上看到了大 O 符號為O(logn)
的模數計算,所以不確定這是否適用於此。 誰能澄清一下?
對於power
,大 O 符號是否會是O(a^b)
因為它涉及冪?
modulo
沒有循環,它只是進行恆定時間運算(數學),所以它是 O(1)。 power
將b
減少 1 直到它為0
,並且 function 的 rest 為 O(1),因此為 O(1*b) 或 O(b)。
按照上一個回答的問題
時間復雜度是針對重復性任務計算的。 因此,如果您通常沒有循環,則不要談論時間復雜度。 你只是應用一件事。
因此,對於modulo
,您可以“忽略它” (O(c)) c is a constant
。
對於recursive function
,由於我們每次都重新進入 function ,直到b==0
,那么復雜度是O(b)
類似於上一個問題中的O(n)
。 ( linear
)
如果你用谷歌搜索Recursion
,它會顯示你的did you mean recursion
,如果你繼續點擊它,它會一直把你帶到同一頁面,因此,遞歸是一項重復性任務。 這就是為什么您認為它類似於循環的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.