简体   繁体   English

这个函数的时间复杂度/大O是不变的吗?

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

is the time complexity of this program O(1)? 是这个程序的时间复杂度O(1)?

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

and if we change int temp to double temp, does the time complexity change as well, or it will remain constant? 如果我们将int temp改为double temp,那么时间复杂度是否也会改变,或者它会保持不变?

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

The answer for the integer part is O(log n) because the value is halved each time. 整数部分的答案是O(log n)因为每次值减半。

The double version starts the same way, except that when the value reaches 1 or close to 1, it doesn't stop and divides until underflow makes it 0. At this point, the number of divisions is fixed. 双版本以相同的方式开始,除了当值达到1或接近1时,它不会停止并分割,直到下溢使其为0.此时,分割数是固定的。

I've made a small empirically calibrated program which tries to predict the number of loops: 我做了一个小的经验校准程序,试图预测循环次数:

#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);

}

I get: 我明白了:

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

So the complexity is O(log n) plus an incompressible number of iterations, depending on the machine. 所以复杂性是O(log n)加上不可压缩的迭代次数,具体取决于机器。

(my apologies for the empiric aspect of my answer, I'm not a floating point expert) (我对我答案的经验方面表示道歉,我不是浮点专家)

For an algorithm to have constant time-complexity, its runtime should stay constant as the number of inputs, n , grows. 对于具有恒定时间复杂度的算法,随着输入数n增加,其运行时应保持不变。 If your function on n = 1 and n = 1000000 takes different amounts of time to run, your function is not O(1) , ie it doesn't have a constant time complexity. 如果n = 1n = 1000000的函数需要不同的运行时间,则函数不是O(1) ,即它没有恒定的时间复杂度。

Let's calculate how many steps the first function takes to terminate: 让我们计算第一个函数终止的步数:

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

For the second, however, it will theoretically keep dividing n by 2 forever, but in reality, it will terminate after some log(n) + c steps, in which case the constant will be omitted, and the complexity is going to be log(n) again. 然而,对于第二个,理论上它将永远地将n除以2,但实际上,它将在一些log(n) + c步之后终止,在这种情况下,常量将被省略,并且复杂性将是log(n)再次。

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

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