Analysis of Algorithm

Time Complexity where loop variable is incremented by 1,2,3,4

Time Complexit
Time Complexity where loop variable is incremented by 1, 2, 3, 4 - Analysis of Algorithm - What is the time complexity of below code?The loop variable ‘i’

What is the Time Complexity where loop variable is incremented by 1,2,3,4 of below code?

void fun(int n)
{
   int j = 1, i = 0;
   while (i < n)
   {
       // Some O(1) task
       i = i + j;
       j++;
   }
}

The loop variable ‘i’ is incremented by 1, 2, 3, 4, … until i becomes greater than or equal to n.

The value of i is x(x+1)/2 after x iterations. So if loop runs x times, then x(x+1)/2 < n. Therefore time complexity can be written as Θ(√n).

READ  Java Programming - Randomized Algorithms (1/2) Approximate Median

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

X