简体   繁体   中英

Time complexity of for loop

Is it O(n) or O(n*n)?

The loop runs approximately n*n times but the loop variable is only one.

I'm confused whether it's O(n) algorithm I think it should be O(n*n) but gfg says it's O(n)

Can anybody help me with the answer??

int j=0;
for(int i=1; i<=n; )
{
   if(j<i)
   {
     j++;
     continue;
   }

   if(j==i)
   {
     i++;
     j=0;
   }
}

I think this loop runs 1 + 2 +... + n times because j needs to be incremented i - 1 times as i grows, and i grows n times. That gives a time complexity of O(n^2).

This is O(1 + 2 +... + n), that is the arithmetic progression, the sum is O(n * (n + 1) / 2), is O(n²).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM