How to write a C program to find the power of 2 in a normal way and in single step?

Showing Answers 1 - 13 of 13 Answers

t.lavanya

  • Jul 9th, 2006
 

if(x && x-1 ==0) printf(" no. is power of 2");

  Was this answer useful?  Yes

Suman

  • Jul 11th, 2006
 

U can take logarithm base 2, and check the result is in interger form or floating point form, u can check whether it is power of 2 or not.

  Was this answer useful?  Yes

farha

  • Jul 30th, 2006
 

Lavanya,

Can u explain logic. The If condition

  Was this answer useful?  Yes

Anurag Laddha

  • Aug 1st, 2006
 

That's actually logical ANDingThe actual to determine whether a number is a power of 2 or not is --> bit wise AND the number under consideration with its previous number. if the result is zero then the number under consideration is power of 2Code: if (x & (x-1) == 0) number is a power of 2else number is NOT a power of two.

  Was this answer useful?  Yes

newbie

  • Aug 4th, 2006
 

what will happen if x is 0?

  Was this answer useful?  Yes

You are right. We should first check whether the given number is larger than 0. If it is larger than 0, we can use (x && (x-1) == 0) to determine whether x is power of 2 or not. If it is 0, then return 0. If x is smaller than 0, what should we do?

  Was this answer useful?  Yes

krisgroup

  • Oct 22nd, 2007
 

Hi folks,

I would say try this ...

int result=!((input_no&&input_no-1)&&input_no)

it works a good bit twidling technique,

chaitanya

  Was this answer useful?  Yes

# include <stdio.h>
# include <conio.h>
void main()
{
 int x;
 printf("Enter the value of x: ");
 scanf(" %d", &x);
 if((x & (x-1)) ==0)
  printf(" no. is power of 2");
    else
      printf(" no. is not power of 2");

 getch();
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions