Calculate the square of a number using bitwise operator.
Truth table of binary multiplication is below:
0 x 0 = 0
0 x 1 = 0
1 x 0 = 0
1 x 1 = 1
Before we look at the coding part, let us perform binary multiplication of 4 and 3.
4 binary is 100
3 binary is 011
Below are the steps:
The above steps can be performed using bitwise operators.
Check if the number is even or odd using bitwise operator.
To check this, we need to look at the rightmost bit. If the rightmost bit is 1 then it is odd else, it is even number.
Hence to achieve this, we use (num & 1), will give us the result.
Example:
Example: For 9: 9 -> 1 0 0 1 1 -> & 0 0 0 1 ------------------- result-> 0 0 0 1 For 14: 14 -> 1 1 1 0 1 -> & 0 0 0 1 ------------------ result-> 0 0 0 0
Solution in C++
#include<iostream> #include<vector> #include<string> using namespace std; void check_even_odd(int num) { if(num & 1) cout<<"The number "<< num<<" is odd"<<endl; else cout<<"The number "<<num<<" is even"<<endl; } void get_square(int num) { int temp = num; int square = 0; int count = 0; while(temp > 0) { if((temp & 1) == 1) { square += num << count; } temp = temp >> 1; count++; } cout<<"The square of the number "<<num<<" is = "<<square<<endl; } int main() { int num = 20; check_even_odd(num); get_square(num); return 0; }
Output:
The number 20 is even The square of the number 20 is = 400