in Algorithms
665 views
1 vote
1 vote
Please help to find the time complexity of this loop.

void main()

{

int n;

while(n>=1)

{

n=n-2;

}

}
in Algorithms
665 views

2 Comments

n/2---> O(n)
1
1
Here the value of n is decreasing by 2.. so the while loop will run for n/2 times..hence it will be O(n)
0
0

1 Answer

1 vote
1 vote
Since each time the n is decreasing by 2 so overall iterations will become half and time complexity=n/2

3 Comments

Yeah I know that it is getting reduced by 2,but why does it becomes half?
0
0
Let us suppose a scenario where n is decreasing by 1 in each loop, so in order to reach 1 it will take n iterations , n=6 to 1 take 6 iterations,now in question here n is decreasing by 2 like if n=6 it will become 4 then 2 and then 0 so the iterations are reduced by half it will take 3 iterations so n/2 time =O(n)
2
2
@Winner,Thank you so much brother. This is where I wanted to get. :).So the instructions will just be half. A tonnes Thanks.
1
1

Related questions

2 votes
2 votes
1 answer
4