Computing Time T(n) and Big-O with an infinite loop

前端 未结 3 1996
半阙折子戏
半阙折子戏 2020-12-04 03:07

I\'m confused on how to create a function T(n) to measure computing time for a nested infinite loop. Here is the code:

x=1;
for(int i = 0;i

        
3条回答
  •  醉梦人生
    2020-12-04 04:05

    Well, in the real world, you're not going to get an answer for obvious reasons, but in math... why not.

    I'll write down the time equation of the function:

    T(n) = n-1 * T(X) 
    

    T(X) is the time for the inner loop. I'll expend it: X1 = initial value of x (in this case 1)

    T(X) = T(X1 * 2) + 1 = T(X1 * 4) + 2 = ... = T(X1 * 2^j) + j
    

    The end condition of this loop is when j >= X1 * 2^j + 1, so we want to solve:

    j >= X1 * 2^j -> j = 2^j -> j <= log2(j).
    

    The above equation has no solution in this Natural Numbers set range, but in Integer set it's easily solved with -1 (actually any integer smaller then 0).

    So, the time complexity for T(n) would be (n-1) * (-1) = 1 - n.

    I don't know what's useful about this, but I hope it'll do the trick for you.

提交回复
热议问题