C Programming: Power of 2 Check šŸŽÆ

beginner
14 min

C Programming: Power of 2 Check šŸŽÆ

Welcome to the exciting world of C programming! Today, we're going to learn about a crucial function - the Power of 2 check. This function helps us determine if a given number is a power of 2. Let's dive in!

Understanding the Power of 2 šŸ“

A number is said to be a power of 2 if it can be written as 2 raised to some power. For example, 1, 2, 4, 8, 16, 32, and so on are all powers of 2.

The Need for a Power of 2 Check Function šŸ’”

In programming, we often need to check if a number is a power of 2. This can be useful in various scenarios such as memory allocation, bit manipulation, and data structures.

Creating the Power of 2 Check Function āœ…

Let's create a simple function called isPowerOfTwo that takes an integer as an argument and returns 1 if the number is a power of 2, and 0 otherwise.

c
#include <stdio.h> int isPowerOfTwo(int number) { // Check if the number is greater than zero if (number <= 0) { return 0; } // Check if the last bit of the number is set (1) if ((number & 1) == 1) { return 0; } // If the number is greater than 1 and the last bit is not set, // the number must be a power of 2 and we can half the number recursively return isPowerOfTwo(number >> 1); }

šŸ’” Pro Tip: The function uses bitwise operators to check the last bit of the number. If the last bit is set, the number is odd and cannot be a power of 2.

Testing the Function āœ…

Now, let's test our function with some examples:

c
int main() { printf("Is 1 a power of 2: %d\n", isPowerOfTwo(1)); // Output: 0 printf("Is 2 a power of 2: %d\n", isPowerOfTwo(2)); // Output: 1 printf("Is 4 a power of 2: %d\n", isPowerOfTwo(4)); // Output: 1 printf("Is 5 a power of 2: %d\n", isPowerOfTwo(5)); // Output: 0 printf("Is 10 a power of 2: %d\n", isPowerOfTwo(10)); // Output: 0 printf("Is 16 a power of 2: %d\n", isPowerOfTwo(16)); // Output: 1 }

Power of 2 Check Function with Logarithmic Time Complexity šŸ’”

The above function has a time complexity of O(log2 n) due to recursion. If you're comfortable with bitwise operations, here's a version of the function with a constant time complexity (O(1)):

c
int isPowerOfTwo_opt(int number) { return (number > 0 && ((number & (number - 1)) == 0)); }

šŸ’” Pro Tip: This function works by using the property that a number is a power of 2 if and only if its binary representation contains only one '1'.

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What does the function `isPowerOfTwo` return if the input number is:

That's it for today! You now have a working Power of 2 check function in C. As you practice more, you'll get more comfortable with bitwise operations and other essential C programming concepts. Happy coding! šŸ’»šŸŒŸ