Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complexity of program having two outer for loop running n times and one for loop running 4 times inside.second for loop

Tags:

algorithm

for($j=1;$j<=$n;$j++)
{
    for($k=1;$k<=4;$k++)
    {
        # o(1) operation
    }
}

for this what i have find out is this will be O(n) times as the constant for loop will run 4n times.

So in this case will it follow the same logic , as it has got one extra for loop , means inside will run 4n times + outer loop:

for($i=1;$i<=$n;$i++)
{
    for($j=1;$j<=$n;$j++)
    {
        for($k=1;$k<=4;$k++)
        {
            #o(1) operation
        }
    }
}

will it be O(n^2) or O(n^2)+O(4)??

like image 696
user3768488 Avatar asked Jan 19 '26 17:01

user3768488


1 Answers

It's O(N2). Since 4 is a constant that is independent of N, it does not change the result of big-O.

Of course the third nested loop does make the program run slower. However, since the slowdown is by a constant factor, the asymptotic timing of the program expressed in big-O notation does not change.

like image 112
Sergey Kalinichenko Avatar answered Jan 22 '26 10:01

Sergey Kalinichenko