English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Hopefully the algorithm is efficient, fast, and uses no loops. If possible, the method will work for any size of int, but if it's not, assume the int is 32 bit.

2007-01-29 05:27:46 · 4 answers · asked by lei514 1 in Computers & Internet Programming & Design

4 answers

yes there is an easy way using a bitwise logical AND operator:

see this article - http://en.wikipedia.org/wiki/Power_of_two

2007-01-29 05:37:15 · answer #1 · answered by Anonymous · 2 0

Since the integer is in binary representation, check to see that one bit and only one bit is set. The exact code would depend on the language you are using and the size of the integer representation on the computer you are using.

Using C++ you could do something like:
#include

using namespace std;

int main()
{
int i=10;
int sum=0;

for (int j=0; j>=1; }

if (sum = 1)
cout << i << " is a power of 2." << endl;
else
cout << i << " is NOT a power of 2." << endl;

return 0;
}

2007-01-29 14:05:26 · answer #2 · answered by SHAWN G 3 · 0 0

it depends what level language you're using

if you have access to decent math, say natural logarithm, then if a number is a power of 2, then its natural logarithm, divided by the natural logarithm of 2, will be an integer

ln(n)/ln(2) = integer, if n is a power of 2

and how do you test for an integer? Well, subtract its integral part (if you have the function) from it, if the rest is non-zero it's not an integer.

here's what this would look like in Excel (I chose Excel because the formulas have to be in one cell and they are not that user friendly, compared to any programming language):

=IF(LN(number)/LN(2)-INT(LN(number)/LN(2))<>0,"no","yes")

of course you can make it more efficient by having a variable equal to ln(number)/ln(2), but you'd need an extra line for this...

in other words: take the natural logarithm of the number, divide it by the natural logarithm of two, then take the integer part of the same, subtract, if the difference is different from zero then it's not a power of 2, write "no", else it is, write "yes".

hope this helps

2007-01-29 13:47:01 · answer #3 · answered by AntoineBachmann 5 · 0 0

hmmmm....

I would write a loop to keep dividing by 2, then check each time to see if the result equals 2 or is less than 2. If its equal to 2, the original number is a power of 2. if its less than 2, stop the loop, its not a power of two.

2007-01-29 13:32:12 · answer #4 · answered by Kutekymmee 6 · 0 0

fedest.com, questions and answers