edited by
472 views
2 votes
2 votes

a)

for(i = 1; i*i <= N; i = 2*i);

b)

for(i = 1; i <= N; i = 2*i);
    for(j = 1; j <= i; j = j+1);

c)

for(i = 1; i*i <= N; i=i+1);
    for(j=1; j <= i ; j=j+1);

d)

for(i = 1; i*i <= N; i=i+1)
    for(j = 1; j <= i ; j = 2*j);
edited by

1 Answer

Best answer
5 votes
5 votes

Using lg for log2

(a)

for(i = 1; i*i <= N; i = 2*i);

i is multiplied by 2 in each iteration and stops when equals √N. So, loop will run for lg (√N) times and time complexity = $\Theta( \lg (\sqrt N ))$

(b)

for(i = 1; i <= N; i = 2*i)
    for(j = 1; j <= i; j = j+1);

Outer loop runs for lg(N) times. For each i, Inner loop runs for i times. So, total number of iterations 

= 1 + 2 + 4 + 8 + ... N (Sum to N terms of GP with a = 1, r = 2, and number of terms = log n)
= $\Theta (N)$ 

(c)

for(i = 1; i*i <= N; i=i+1)
    for(j=1; j <= i ; j=j+1);

The outer loop runs for √N times. For each i, the inner loop runs i times. So, number of iterations 

= 1 + 2 + ... + √N

= √N * (√N+1) /2 = $\Theta (N)$

(d)

for(i = 1; i*i <= N; i=i+1)
    for(j = 1; j <= i ; j = 2*j);

The outer loop runs for √N times. For each i the inner loop runs lg i times. So, total number of iterations

= lg 1 + lg 2 + lg 3 + ... lg √N
=lg (1 * 2 * 3 * ... *√N)
=lg ((√N)!)
= $\Theta (√N \lg √N)$ using Stirling's approximation)
http://mathworld.wolfram.com/StirlingsApproximation.html

selected by

Related questions

2 votes
2 votes
2 answers
1
Amar Vashishth asked Aug 2, 2015
2,432 views
int fun(int n) { int count=0; for (int i= n; i 0; i/=2) for(int j=0; j< i; j++) count+= 1; return count; }
0 votes
0 votes
3 answers
2
gshivam63 asked May 19, 2016
2,897 views
int f(int x){if(x<1) return 1;else return f(x-1) +g(x/2);}int g(int x){if(x<2) return 1;else return f(x-1) +g(x/2);}a. LogarithmicB. QuadraticC. LinearD. Exponential
8 votes
8 votes
2 answers
3