Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
|
Implementation to check whether a number is a power of 2 or not. More...
#include <iostream>
Namespaces | |
namespace | math |
for std::rand | |
Functions | |
void | math::power_of_two (int n) |
Function to test above algorithm. More... | |
int | main () |
Main function. More... | |
Implementation to check whether a number is a power of 2 or not.
This algorithm uses bit manipulation to check if a number is a power of 2 or not.
Let the input number be n, then the bitwise and between n and n-1 will let us know whether the number is power of 2 or not
For Example, If N= 32 then N-1 is 31, if we perform bitwise and of these two numbers then the result will be zero, which indicates that it is the power of 2 If N=23 then N-1 is 22, if we perform bitwise and of these two numbers then the result will not be zero , which indicates that it is not the power of 2
int main | ( | void | ) |
Main function.
n stores the input from the user
function call with
n |