简体   繁体   中英

T(n) for a nested loop

Can someone help me find the T(n), the number of times the inner loop will run as a function of n, for the following loops:

for (int i = 0; i < n; i++)
    for (int j = i; j > 0; j /= 2)
        cout << j << endl;

Just looking at this i know that the big-O is O(n*log(n)) but i am also supposed to figure out the T(n)

I have ran the code and found the number of times the statement is executed. i have figured out a series but i have not figured out how to simplify it:

log_2(n-1)+1+log_2(n-2)+1+log_2(n-3)+1+.......

I have tried to use the logarithmic product rule to simplify it to

T(n)=log_2((n-1)!2^2)) 

but that does not satisfy the equations.

*edited to explain what i meant by T(n)

By T(n) , I think you mean a function for the number of "fundamental operations" for an input of size n . First you have to pick a "fundamental operation". In this case, cout << j << endl seems like a reasonable choice.

Let's build up from some simpler examples:

for (int i = 0; i < n; i++)
    cout << i << endl;

(Since I can't do sigma notation here, I will write sum(a, b, c) where a is normally written below the sigma, b is written above the sigma, and c is written to the right of the sigma.)

The analysis of a for loop is based on a summation. We execute each output operation once, so T(n) = sum(i = 0, n - 1, 1) . We can prove by mathematical induction that T(n) = n .

Since this is identical to your outer for loop, we can write T(n) = sum(i=0, n, THE NUMBER OF STEPS FOR THE INNER LOOP) .

To analyze the inner loop, let's start by noting if we count in the opposite direction:

for (int i = n; i > 0; i--)
    cout << i << endl;

the analysis is the same.

Now let's do something a little more complex:

for (int i = n; i > 0; i /= 2)
    cout << i << endl;

We need to count the steps using sigma notation, so we will transform the code a few times while preserving the number of steps executed. In the same way that our previous counting examples have the same number of steps, we can write this as

for (int i = 0; i < n; i *= 2)
    cout << i << endl;

I understand the output will be different, but we are only concerned about the number of steps.

We need to make one more transformation since sigma notation always increments by one:

for (int i = 0; i < n/2; i++)
    cout << i << endl;

Now this looks a lot like our first example: T(n) = sum(i=0, n/2 - 1, 1) = n/2 .

So now we can add the summation of the inner loop to our function:

T(n) = sum(i=0, n, sum(j=i, n/2 - 1, 1))

The final step is to solve this summation for a closed formula. This is left as an exercise for the reader.

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