| Author |
Message |
kad
Joined: 08 Feb 2005 Posts: 24
|
19 Jul 2006 19:55 solution needed |
|
|
|
|
| could anybody give a one line c expression to test if a number is a power of 2 or not?
|
|
| Back to top |
|
 |
Anno
Joined: 08 Feb 2006 Posts: 114 Helped: 15 Location: South Africa
|
19 Jul 2006 20:20 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;
}
|
|
|
| Back to top |
|
 |
booklog
Joined: 22 Jun 2006 Posts: 53 Helped: 3
|
20 Jul 2006 8:05 Re: solution needed |
|
|
|
|
| (number & 0x01) ? printf(" Number is odd\n") :printf("Number is even\n");
|
|
| Back to top |
|
 |
tronix
Joined: 06 Jul 2006 Posts: 121 Helped: 6
|
20 Jul 2006 8:41 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)
|
|
| Back to top |
|
 |
cfant
Joined: 04 Apr 2001 Posts: 177 Helped: 18
|
22 Jul 2006 4:55 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
|
|
| Back to top |
|
 |
naresh850
Joined: 09 Jun 2006 Posts: 147 Helped: 1
|
08 Oct 2006 7:34 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" );
}
|
|
| Back to top |
|
 |