Reputation: 27
I am having difficulty figuring out the big o notation running time of this piece of code. I would think it's O(n) because i=0 and the first while loop keeps going until i = n but then the second while loop comes in and the whole thing is throwing me off.
i=0
sum = 0;
while i<n:
sum++
if i==3 or i==7 or i==5:
j=0
while j<n:
sum++
j++
i++
Upvotes: 1
Views: 192
Reputation: 1819
It indeed is O(n)
. If you had no if statements you would have O(n^2)
. But inner loop is running at most 3 times so it is equivalent to O(3n)
and O(n)
.
Upvotes: 2
Reputation: 11
It's still O(n). The second while loop take 3n time in the worse case .( n>=8)
Upvotes: 1
Reputation: 531055
The inner loop only executes, at most, 3 times. For large values of n
, the total time spent in that loop will be inconsequential to the overall running time.
Upvotes: 1