简体   繁体   中英

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

is the time complexity of this program 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?

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.

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.

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.

(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. 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.

Let's calculate how many steps the first function takes to terminate:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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