Check if a number is multiple of 9 using bitwise operators in C++
Hello everyone, In this tutorial, we will discuss how to check if a number is multiple of 9 using the bitwise operators in C++. There are many other ways to check for the same as well such as, The most general way to check for any number “x” divisibility by 9 is to do x%9.
Whereas, In this case, we discuss how to do it using the bitwise operators.
Check if a number is multiple of 9 using bitwise operators
For checking any number we are using a function:
bool check(int x)
which is being called recursively, in which it checks for 3 factors which are:
- if (x == 0 || x == 9)
- if (x < 9)
- check((int)(x>>3) – (int)(x&7))
where x is the number that you wish to check.
//code by Vivek Kr. Jaiswal
#include<iostream>
using namespace std;
bool check(int x)
{
if (x == 0 || x == 9)
return true;
else if (x < 9)
return false;
else
return check((int)(x>>3) - (int)(x&7));
}
int main()
{
int x;
cout << "Enter any number to check whether is a multiple of 9:" << endl;
cin >> x;
if( check(x) )
cout << "Provided Number is multiple of 9 \n" << endl;
else
cout << "Provided Number is not multiple of 9 \n" << endl;
return 0;
}Output: Enter any number to check whether is a multiple of 9: 81 Provided Number is multiple of 9
I hope I have made my point clear and simple, do comment in the comment box if you wish to know more about any topic.
You may also visit:
Thank You.
Leave a Reply