0
int i=1,s=1;
while(s<=n)
{
i++;
s=s+i;
}

time complexity for this is O(root(n)). I do not understood it how. since the series is going like 1+2+...+k . please help.

SeasonalShot
  • 2,357
  • 3
  • 31
  • 49

3 Answers3

2

Let the loop execute x times. Now, the loop will execute as long as s is less than n.

We have :

After 1st iteration :
s = s + 1
After 2nd iteration :
s = s + 1 + 2

As it goes on for x iterations, Finally we will have

1 + 2 ... + x <= n

=> (x * (x + 1)) / 2 <= n

=> O(x^2) <= n

=> x= O (root(n))

axiom
  • 8,765
  • 3
  • 36
  • 38
2

s(k) = 1 + 2 + 3 + ... k = (k + 1) * k / 2

for s(k) >= n you need at least k steps. n = (k + 1) * k / 2, thus k = -1/2 +- sqrt(1 + 4 * n)/2;

you ignore constants and coeficients and O(-1/2 + sqrt(1+4n)/2) = O(sqrt(n))

V-X
  • 2,979
  • 18
  • 28
0

This computes the sum s(k)=1+2+...+k and stops when s(k) > n.

Since s(k)=k*(k+1)/2, the number of iterations required for s(k) to exceed n is O(sqrt(n)).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • how did you figure out the O(sqrt(n)) part? Do we need to solve it ? or in problems if i find "s(k)=k*(k+1)/2" this, can i directly assume it to be O(sqrt(n)? – SeasonalShot Mar 02 '13 at 13:42