javatime-complexitybig-odiscrete-mathematics

How do you calculate T(n) in an equation from a code fragment?


I'm having trouble converting code fragments into equations that figure out T(n) of said equation. An example code fragment is this:

a = b + c; d = a + e;

This specific questions asks to determine T(n). How would I go about doing that? Another example code given is as follows:

sum = 0;
for (i=0; i<3; i++)
    for (j=0; j<n; j++)
        sum++;

I've attempted to follow instruction and examples from other questions that are similar, but am getting stuck on how the equation is found exactly. Here's an example and result that I know of so far:

Code:

sum = 0;
i = 1;
while (i <= N)
{
    sum = sum + 1;
    i++;
}

With the result being this: T(N) = 2 + (Σ with N on top and i+1 on bottom) * 2 and that ends up simplifying to 2+2N I'm unsure of how this result is found though.


Solution

  • Here is how you can approach this problem:

    sum = 0;                 // 1 - O(1)
    for (i=0; i<3; i++)      // This will run 3x times - O(3)
        for (j=0; j<n; j++)  // This will run n times (O(n)), meaning the sum will be increased n times 
            sum++;
    

    Then you can write T(n)=1+3*(1+n+2n)≈1+3n. This means that the time complexity for this code is O(n).

    Generally, when looking at the simple for loop, like the one here, you can determine its complexity by looking at the condition statement. For j<n the complexity will be O(n), and for i<3 the complexity will be O(3).