簡體   English   中英

如何計算以下算法的時間復雜度

[英]How to calculate time complexity of the following algorithm

如何計算以下算法的時間復雜度。 我嘗試過,但由於遞歸調用而感到困惑。

power (real x, positive integer n)
//comment : This algorithm returns xn, taking x and n as input
{
    if n=1 then
    return x;
    y = power(x, |n/2|)
    if n id odd then
    return y*y*x //comment : returning the product of y2 and x
    else
    return y * y //comment : returning y2
}

可以用簡單的步驟來解釋一下。

為了弄清遞歸函數的時間復雜度,您需要計算將要根據某些輸入變量N進行的遞歸調用的次數。

在這種情況下,每個調用最多進行一個遞歸調用。 調用次數約為O(log 2 N),因為每次調用都會使N減少一半。

遞歸函數的其余部分為O(1),因為它不依賴於N 因此,您的函數的時間復雜度為O(log 2 N)。

每個調用都被視為固定時間操作,並且它將遞歸多少次等於您可以在n = 1之前執行n / 2次,這最多是log 2n )次。 因此,最壞情況下的運行時間為O(log 2 n )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM