TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
power_of_two.cpp File Reference

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

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

Go to the source code of this file.

Namespaces

namespace  math
 for assert
 

Functions

int math::power_of_two (int n)
 This function finds whether a number is power of 2 or not.
 
static void test ()
 Self-test implementations.
 
void user_input_test ()
 Take user input in the test cases (optional; currently commented)
 
int main ()
 Main function.
 

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

Definition in file power_of_two.cpp.

Function Documentation

◆ main()

int main ( void )

Main function.

Returns
0 on exit

Definition at line 99 of file power_of_two.cpp.

99 {
100 test(); // run self-test implementations
101
102 // uncomment the line below to take user inputs
103 //user_input_test();
104
105 return 0;
106}
static void test()
Self-test implementations.

◆ test()

static void test ( )
static

Self-test implementations.

Returns
void

Definition at line 59 of file power_of_two.cpp.

59 {
60 std::cout << "First case testing... \n"; // for n = 32 return 1
61 assert(math::power_of_two(32) == 1);
62 std::cout << "\nPassed!\n";
63
64 std::cout << "Second case testing... \n"; // for n = 5 return 0
65 assert(math::power_of_two(5) == 0);
66 std::cout << "\nPassed!\n";
67
68 std::cout << "Third case testing... \n"; // for n = 232 return 0
69 assert(math::power_of_two(232) == 0);
70 std::cout << "\nPassed!\n";
71
72 std::cout << "\nAll test cases have successfully passed!\n";
73}
int power_of_two(int n)
This function finds whether a number is power of 2 or not.

◆ user_input_test()

void user_input_test ( )

Take user input in the test cases (optional; currently commented)

Returns
void

function call with

Parameters
n

Definition at line 79 of file power_of_two.cpp.

79 {
80 int n = 0; // input from user
81
82 std::cout << "Enter a number " << std::endl;
83 std::cin >> n;
84
87 if (result == 1) {
88 std::cout << "Yes, the number " << n << " is a power of 2\n";
89 }
90 else {
91 std::cout << "No, the number " << n << " is not a power of 2\n";
92 }
93}
uint64_t result(uint64_t n)