Discussion Forum on time complexity, self referential structure (Week 2)

Discussion Forum (Week 2)

Discussion Forum (Week 2)

by Md. Atikur Rahman -
Number of replies: 0

1.Importance time complexity :-

The time complexity of an algorithm is the total amount of time required by an algorithm to complete its execution. In simple words, every piece of code we write, takes time to execute. The time taken by any piece of code to run is known as the time complexity of that code. The lesser the time complexity, the faster the execution.

 

2. Find out the time complexity and errors from the code :-

#include <stdio.h>

int main() {

    int counter, N,i;

 printf("Enter a Positive Number\n");

    scanf("%d",&N);

   for (counter = 1; counter <= N; counter++)

       {

            printf("%d \n", counter);

       }

     int a=12,n=12;

    if(N>10)

        {

        for(i=0; i<a; i++)

        {

             for(i=0; i<a; i++)

                {

                     a++;

                }

            }

      for(i=0;i<a;i*=2)

        {

         printf("hello");

        }

    }

    return 0;

}

 

From this code we find out 3 errors.

(a). Declare the variable i;

(b). We added for before (counter = 1; counter <= N; counter++)

(c). We added semicolon (;) after printf("hello");

Those are the errors of the code.

 

Time complexity for the code :-

According to the codeblocks, We see,

Line 7 : a  loop of size N.

Line 13 to 20 : Size of loop n^3 and one operations.

So, We get, N + n^3

Again, when we have an asymptotic analysis, we drop all constants and leave the most important term: n^3. So, in big O notation, it would be O(n^3).