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
Algorithm complexity is only defined for algorithms, which by (the most often accepted) definition must terminate. This process doesn't terminate (except "in practice" as Marcelo notes; i.e. as a program on a real machine vs. in theory on a theoretical Turing machine with an infinite tape and all the time in the world) so is not an algorithm. So it has no "algorithmic time complexity".
Trying to determine the algorithmic complexity for a non-algorithm is a futile exercise, as is trying to express its running time as a polynomial if it's an infinite process.
The Big-O complexity of a genuinely infinite loop is undefined. Here's why:
The definition for Big O notation says that:
f(N) = O(g(N))
if and only iff(n) <= |M g(n)|
for some constantM
, and for alln >= n0
However, the prerequisite is that f(n)
and g(n)
are functions on some subset of the Real numbers.
In the case of an infinite loop, the value of f(n)
is "infinity" which is not a Real number. Hence, we cannot apply Big O notation to the problem (of a genuinely infinite loop) in a way that makes mathematical sense.
(The Wikipedia page on Big O Notation states this more formally.)
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.