簡體   English   中英

這個函數的時間復雜度/大O是不變的嗎?

[英]Is the time complexity/Big O of this function a constant?

是這個程序的時間復雜度O(1)?

f1(int n){
  int temp = n;
  while (temp /= 2))
  {
    len++; result+=m;
  }
}

如果我們將int temp改為double temp,那么時間復雜度是否也會改變,或者它會保持不變?

f2(int n){
  double temp = (double)n;
  while (temp /= 2))
  {
    len++; result+=m;
  }
}

整數部分的答案是O(log n)因為每次值減半。

雙版本以相同的方式開始,除了當值達到1或接近1時,它不會停止並分割,直到下溢使其為0.此時,分割數是固定的。

我做了一個小的經驗校准程序,試圖預測循環次數:

#include <stdio.h>
#include <math.h>

void f2(int n){
  int len=0;
  double temp = (double)n;
  while (temp /= 2)
  {
    len++; 
  }
  // 1.53 is an empiric constant, maybe it could be theorically computed
  // it was just to make the numbers match
  printf("%d %lf\n",len,log(n)*1.53+1074);
}
int main()
{

    f2(100000000);
    f2(10000000);
    f2(1000000);
    f2(10000);
    f2(100);
    f2(1);

}

我明白了:

1101 1102.183642
1097 1098.660686
1094 1095.137731
1087 1088.091821
1081 1081.045910
1074 1074.000000

所以復雜性是O(log n)加上不可壓縮的迭代次數,具體取決於機器。

(我對我答案的經驗方面表示道歉,我不是浮點專家)

對於具有恆定時間復雜度的算法,隨着輸入數n增加,其運行時應保持不變。 如果n = 1n = 1000000的函數需要不同的運行時間,則函數不是O(1) ,即它沒有恆定的時間復雜度。

讓我們計算第一個函數終止的步數:

n / 2 x =1⇒x= log(n)

然而,對於第二個,理論上它將永遠地將n除以2,但實際上,它將在一些log(n) + c步之后終止,在這種情況下,常量將被省略,並且復雜性將是log(n)再次。

暫無
暫無

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

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