How to write 4 different functions that check if a number is a power of 2 in C++

2 Answers

0 votes
#include <iostream>
#include <bit>
#include <cmath>

using std::cout;

// 1) Bitwise trick: x & (x - 1) == 0
bool is_power_of_two_a(unsigned int x) {
    return x != 0 && (x & (x - 1)) == 0;
}

// 2) Count bits using std::popcount (C++20)
bool is_power_of_two_b(unsigned int x) {
    return x != 0 && std::popcount(x) == 1;
}

// 3) Using std::has_single_bit (C++20)
bool is_power_of_two_c(unsigned int x) {
    return std::has_single_bit(x);
}

// 4) Using logarithms (educational)
bool is_power_of_two_d(unsigned int x) {
    if (x == 0) return false;
    double y = log2(x);
    return floor(y) == y;
}

int main() {
    unsigned int a = 64;   // true
    unsigned int b = 70;   // false

    cout << std::boolalpha;

    cout << "Testing " << a << ":\n";
    cout << is_power_of_two_a(a) << "\n";
    cout << is_power_of_two_b(a) << "\n";
    cout << is_power_of_two_c(a) << "\n";
    cout << is_power_of_two_d(a) << "\n\n";

    cout << "Testing " << b << ":\n";
    cout << is_power_of_two_a(b) << "\n";
    cout << is_power_of_two_b(b) << "\n";
    cout << is_power_of_two_c(b) << "\n";
    cout << is_power_of_two_d(b) << "\n";
}



/*
OUTPUT: 

Testing 64:
true
true
true
true

Testing 70:
false
false
false
false
  
*/

 



answered Apr 1 by avibootz
0 votes
#include <iostream>
#include <cmath>

using std::cout;

// 1) Bitwise trick
bool is_power_of_two_a(unsigned int x) {
    return x != 0 && (x & (x - 1)) == 0;
}

// 2) Count bits using builtin popcount
bool is_power_of_two_b(unsigned int x) {
    return x != 0 && __builtin_popcount(x) == 1;
}

// 3) Manual bit counting
bool is_power_of_two_c(unsigned int x) {
    int c = 0;
    while (x) {
        c += x & 1;
        x >>= 1;
    }
    return c == 1;
}

// 4) Using logarithms
bool is_power_of_two_d(unsigned int x) {
    if (x == 0) return false;
    double y = log2(x);
    return floor(y) == y;
}

int main() {
    unsigned int a = 64;   // true
    unsigned int b = 70;   // false

    cout << std::boolalpha;

    cout << "Testing " << a << ":\n";
    cout << is_power_of_two_a(a) << "\n";
    cout << is_power_of_two_b(a) << "\n";
    cout << is_power_of_two_c(a) << "\n";
    cout << is_power_of_two_d(a) << "\n\n";

    cout << "Testing " << b << ":\n";
    cout << is_power_of_two_a(b) << "\n";
    cout << is_power_of_two_b(b) << "\n";
    cout << is_power_of_two_c(b) << "\n";
    cout << is_power_of_two_d(b) << "\n";
}



/*
OUTPUT: 

Testing 64:
true
true
true
true

Testing 70:
false
false
false
false
  
*/

 



answered Apr 1 by avibootz

Related questions

...