• recategorized by
4,804 views
3 3 votes
what will be time complexity of this program?

void function(int n)
{
    int count = 0;
    for (int i=0; i<n; i++)
    {
        for (int j=1; j< i*i; j++)
        {
            if (j%i == 0)
            {
                for (int k=0; k<j; k++)
                    printf("*");
            }
        }
    }
}

3 Answers

4 4 votes

Answer: $O(n^4)$

The “printf("*");” statement is running the maximum no. of times. So, the Time complexity is actually how many times the “printf("*"); statement is running. I have unraveled every loop so that the actual number of execution can be determined and to prove that the program is actually depending on the $if$ statement:-

So the “printf("*");” statement is running $O(n^4)$ times, The time complexity of the program is $O(n^4)$. 

–1 –1 vote

void function(int n)
{
    int count = 0;
    for (int i=0; i<n; i++)
    {
        for (int j=1; j< i*i; j++)
        {
            if (j%i == 0)
            {
                for (int k=0; k<j; k++)
                    printf("*");
            }
        }
    }
}

Here the innermost loop will run maximum when

j=(n^2)-1   

so the T.C of innermost loop will be  =  O(n^2)

now the middle loop 

i.e   for (int j=1; j< i*i; j++)

this will run maximum when i=n-1

and as the constraint here is  j<i*i  thus   T.C = O(n^2)

now coming to the outermost loop it is clearly running n times

thus T.C = O(n)

the overall T.C = n*n^2*n^2

it will be O(n^5). 

Position:
Show:

Related questions

0 0 votes
2 2 answers
1.9k
1.9k views
anon1 asked Feb 13, 2022
1,876 views
Can anyone explain this?
1 1 vote
1 answers 1 answer
284
284 views
tarunmundriya asked Dec 27, 2025
284 views
Consider the network that uses CSMA/CD, consists of four hosts and the distribution of this network is shown below:Distance between O and M = 30 kmDistance between M and ...
2 2 votes
2 2 answers
534
534 views
ykaran12x asked Dec 2, 2024
534 views
If a 5000 bytes datagram from the transport layer arrives at the network layer and needs to be sent through a link with a maximum transferable unit of 1000 bytes, includi...
3 3 votes
2 2 answers
626
626 views
eggs asked Nov 24, 2024
626 views
Consider a hypothetical CPU that supports the following instruction set:- $\text{ADD } R_i, R_j$ - $\text{SUB } R_i, R_j$ - $\text{MOV } R_i, R_j$ - $\text{AND } R_i, ...