edited by
1,812 views
2 votes
2 votes
For(i=1;i<(1<<n);i++)
{
Do something
}

What is the meaning of the expression in the condition part of the for loop?

edited by

2 Answers

Best answer
9 votes
9 votes

$\lt\lt$ is Left Shift operator.

 100(4 in decimal) << 1 == 1000 (8)( which is equivalent to multiplying by 2) 
 1 << 2 == 100 (4 in decimal)

So, $1 \lt\lt n$ means $1$ is being shifted by $n$ bit positions.

$\large \color{green}{ 1 \lt\lt n  = 2^{n}}$

Index $i$ starts with $ i = 1 $ and goes till $ i \lt 2^{n} $. So, total no. of times loop executes is $2^{n}-1$

So, Time complexity of Above code is :  $ O(2^n) $

selected by
4 votes
4 votes

I have modified your code for better undrstanding

  #include <stdio.h>
    int main()
    {
 	    int i,c=0 ,n=8;                              //const time say (a )
		for(i=1;i<=(1<< n);i++)
		{
    	c=c+1;  
		}

		printf("\n %d ",c );
    }

Here , Time complexity is nothing but home many times the loop gets executed . 
 

 1 << n

This means that 1 is being left shifted 'n' bit positions .

that ie  1 << 3 $\Rightarrow$  0000 0001 left shifted 3 bit positions 0000 1000 becomes 8 it is nothing but $2^{3}$

Now, lets get back to our problem ,

for i= 1  loop gets executed $2^{1} - 1$ $\Rightarrow$ 2-1 time
for i= 2  loop gets executed $2^{2} - 1$ $\Rightarrow$ 4-1 time
for i= 3  loop gets executed $2^{3} - 1$ $\Rightarrow$ 8-1 time
for i= n  loop gets executed $2^{n} - 1$ $\Rightarrow$ 2n-1 time

Therefore Time Complexity of the code is $\Theta(2^{n})$

Related questions

0 votes
0 votes
1 answer
1
saptarshiDey asked Jan 3, 2019
8,160 views
What will be the worst case time complexity for the following code segment?int count=0,N; for(i=0;i<N*2;i++){ for(j=0;j<i/3;i++){ for(k=0;k<j*j;k++){ count++; } } }Option...
1 votes
1 votes
1 answer
2
0 votes
0 votes
2 answers
3
kalpashri asked May 12, 2015
577 views
for(i=1;i<=n;i=i*2);for(j=1;j<=i;j=j+1);{}
1 votes
1 votes
2 answers
4
sh!va asked Dec 4, 2016
958 views
for (int i = 1; i <=m; i += c){ -do something -}for (int i = 1; i <=n; i += c){ -do something - }What will the the tiem complexity of given code pseudococde?A. O (m...