Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
power_of_two.cpp File Reference

Implementation to check whether a number is a power of 2 or not. More...

#include <iostream>
Include dependency graph for power_of_two.cpp:

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...
 

Detailed Description

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.

Algorithm

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

Note
This implementation is better than naive recursive or iterative approach.
Author
Neha Hasija

Function Documentation

◆ main()

int main ( void  )

Main function.

Returns
0 on exit

n stores the input from the user

function call with

Parameters
n
58 {
59 int n = 0;
60 /// n stores the input from the user
61 std::cout << "enter a number " << std::endl;
62 std::cin >> n;
63 /// function call with @param n
65 return 0;
66}
T endl(T... args)
void power_of_two(int n)
Function to test above algorithm.
Definition: power_of_two.cpp:36
Here is the call graph for this function: