Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the time complexity of these simple loops calculated?

I understand how:

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

This time complexity is O(n).

for (int i=0; i<n; i++)
    for (int j=0; j<n; j++)
        for (k=0; k<n; k++)

this is O(n^3) right?

i=1
do
    //......
    i++
while (i*2 <n)  

Is this O(n)? Or is it exactly O(n/2)?

like image 205
anna Avatar asked Jan 19 '26 09:01

anna


1 Answers

O(n/2) is O(n) only with a constant coefficient of 1/2. The coefficient can be 10 billion, it would still be O(n), and not e.g. O(n^(1.0001)) which is a different complexity class.

like image 57
Sebastian Avatar answered Jan 23 '26 20:01

Sebastian