C line for testing if a number is a power of 2 or not

Status
Not open for further replies.

kad

Junior Member level 2
Joined
Feb 8, 2005
Messages
24
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
199
could anybody give a one line c expression to test if a number is a power of 2 or not?
 

Re: solution needed

Well the following code works only for integers
Code:
#include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;

int main()
{
	int x= 10;
	double intx;
	cout<<"Give a number :";
	cin>>x;
	cout<<"Square Root of "<<x<<" :" <<sqrt(x)<<endl;
	if(modf(sqrt(x),&intx)!=0)    //one line testing
                cout<<"Not sqrt thingy"<<endl;
	return 0;
}
 

Re: solution needed

(number & 0x01) ? printf(" Number is odd\n") rintf("Number is even\n");
 

Re: solution needed

this s d smallest I can think of

let say x is d no.

ans=yes;
while(x>1)
{
if((x%2)==1) {ans=no ; break ;}
x=x/2;
}

ans will give weather no. is 2's power or not.
note:1 will be considered yes (2^0)
 

Re: solution needed

#include <stdio.h>

int main(void)
{
int i;

for(i=2; i<100; i++)
{
if ( !(i & (i-1)))
printf("%d is power of 2\n", i);
}
return 0;
}

will give you:


2 is power of 2
4 is power of 2
8 is power of 2
16 is power of 2
32 is power of 2
64 is power of 2
 

Re: solution needed

int x= 32768;
int power = 0;
char flag ;

///////////////////////////////////////////////////////////////////////////////
void main (void)
{
flag = 1;
while(x>1)
{
if((x%2)==1) {flag=0 ; break ;}
x=x>>1; power++;
}
if (flag == 1) printf("x is %d power of 2",power );
else printf("x is not power of 2" );
}
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…