# Thread: Help with checking, raising to the power of 2

1. ## Help with checking, raising to the power of 2

Hi all, I am trying to raise an integer to the closest power of 2 (if already not one). Now in order to do this I first check for whether the number (say n) is power of 2. If it is , then I return. Now for doing this check I loop over integers :

example

Code:
```int raise(int n)
{
for(int i=0;i<=n;i++)
{
temp=2**i;

if(n == temp)
return n;

if(temp > n)
{
n=temp;
return n;
}

}
}```
I was wondering whether this is the most efficient method(which I am sure isn't especially when one considers the for loop). I know that probaly bitwise operations (XOR, AND etc.) could be used for the same and would be more efficient in a way. Could someone help me improve the effieciency of this

2. to begin with:
Code:
`temp=2**i;`
** isn't a valid operator

Now when you said
raise an integer to the closest power of 2 (if already not one).
I assume you mean round the integer up to the closest power of 2 (i.e 3 because 4, 5 becomes 8, 9 because 16, etc). Unless you build an array of integers that represent all powers of 2 there is no way to avoid some type of looping.

An easy way would be to start from 1 ( 2 raised to 0 = 1) and keep multiplying by 2 until you reach your number or have exceeded your number.

If you reach your number then you know its a power of 2 and if you exceed your number then you know it wasn't but you've got the next power of 2

Quasi psuedo:
Code:
```int raise(int n)
temp = 1
while ( temp < n )
temp <- temp * 2
return temp```

3. sorry I used Fortran syntax. I guess in C++/C ,can one use the pow() function instead?

Code:
```int raise(int n)
{
for(int i=0;i<=n;i++)
{
temp=pow(2,i)
if(n == temp)
return n;

if(temp > n)
{
n=temp;
return n;
}

}
}```
but I am sure some bitwise operations could be used too...

4. Well, you could use <<

I'm not sure how the speed of that compares to using the pow function though.

5. exactly ... how do i use say '<<' to do the same?

6. If the log of base2 to any number is a whole number...than it is a power of 2, and your result is that power of two it is. But in c++ you can not specify log base so you must use natural log to convert.
*edit*

Code:
```	int input;
cin >> input;

double math;

math = ( (log(input))/(log(2)) );

cout << math;```
That is probably the most efficent way to check if it is a power of 2.
If it is 2, it will be a whole number (and whatever that number is, it is that power of two). You just have to check if it is a whole number.

And if it is not a whole number, the next whole number is the next closest power of 2.

And you can change that hardcoded 2 to any number, and it will check for that power. Or the user can input it in, ect.

When ever you are trying to do something with powers and exponets , make sure to look into logs.
+,-
*,/
exponets,logs