Understanding whether a number is even or odd is one of the most common tasks in programming. While most beginners use the arithmetic modulus operator (%), there’s a faster and more efficient alternative the bitwise AND operator (&).
In this post, we'll explore both approaches, compare them, and understand why bitwise is better.
Approach 1: Using Arithmetic Operator.
The most common and straightforward method is using the modulus operator (%). If a number divided by 2 leaves a remainder of 0, it's even. Otherwise, it's odd.
if (n % 2 == 0) → Even
else → Odd
// C++ Example: Find Number is Odd or Even
#include <iostream>
using namespace std;
void checkEvenOrOdd_Arithmetic(int n) {
if (n % 2 == 0)
cout << n << " is Even" << endl;
else
cout << n << " is Odd" << endl;
}
6 is Even
Approach 2: Using Bitwise AND Operator.
A faster and smarter way to check if a number is even or odd is using bitwise operators.
The & operator performs a bit-by-bit comparison between two numbers.
For each bit, it returns:
- 1 if both bits are 1
- 0 otherwise
When you perform n & 1, you're checking the Least Significant Bit (LSB) of the number.
- If LSB is 0 → number is even
- If LSB is 1 → number is odd
Because the binary of even number always end with 0 and binary of odd number always end with 1. Let's understand this with few examples:
Example 1:
Number = 4 Binary of 4: 0100 Binary of 1: 0001 0100 AND 0001 = 0000 → 0 → Even
Example 2:
Number = 7 Binary of 7: 0111 Binary of 1: 0001 0111 AND 0001 = 0001 → 1 → Odd
Example Code:
//C++ Example: Find Even and Odd Using Bitwise AND
#include <iostream>
using namespace std;
void checkEvenOrOdd_Bitwise(int n) {
if (n & 1)
cout << n << " is Odd" << endl;
else
cout << n << " is Even" << endl;
}
int main() {
checkEvenOrOdd_Bitwise(4);
return 0;
}
6 is Even
No comments
Post a Comment