Reputation: 2579
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.
Upvotes: 0
Views: 2268
Reputation: 8995
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))
Upvotes: 3
Reputation: 3029
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))
Upvotes: 3
Reputation: 500427
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))
.
Upvotes: 0