

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write an Efficient Method to Check if a Number is Multiple of 3 in C++
Here, we need to write a program that is used to check if the given number is a multiple of 3 or not.
A general solution is a trivial solution, adding all the digits of the number and if the sum is a multiple of three then the number is divisible by 3 else not. But this solution is not the most efficient one.
An efficient solution will be using the bit count in the binary representation of the number. If the difference between the count of set bits at odd position and the count of set bits at even position is a multiple of 3 then the number is a multiple of 3.
We will use a loop and shift the bits of the number and count the number of bits that are even and odd positions. At last, we will return the check if the difference is a multiple of three.
Let’s take an example to understand the implementation,
Input
n = 24
Output
even
Explanation
binary representation = 11000 Evensetbits = 1 , oddsetbits = 1. Difference = 0, it is divisible.
Program to show the implementation of our solution,
Example
#include <bits/stdc++.h> using namespace std; int isDivisibleBy3(int n) { int oddBitCount = 0; int evenBitCount = 0; if (n < 0) n = -n; if (n == 0) return 1; if (n == 1) return 0; while (n) { if (n & 1) oddBitCount++; if (n & 2) evenBitCount++; n = n >> 2; } return isDivisibleBy3(oddBitCount - evenBitCount); } int main() { int n = 1241; cout<<"The number "<<n; if (isDivisibleBy3(n)) cout<<" is a multiple of 3"; else cout<<" is not a multiple of 3"; return 0; }
Output
The number 1241 is not a multiple of 3
- Related Questions & Answers
- An efficient way to check whether n-th Fibonacci number is multiple of 10?
- Write an Efficient C Program to Reverse Bits of a Number in C++
- Write a C# program to check if the entered number is Armstrong number?
- Check if binary string multiple of 3 using DFA in Python
- Write a C# program to check if a number is Palindrome or not
- Write a C# program to check if a number is divisible by 2
- Write a C# program to check if a number is prime or not
- Check if any permutation of a number is divisible by 3 and is Palindromic in Python
- Check if a large number is divisible by 3 or not in java
- Check if a large number is divisible by 3 or not in C++
- Check if a number is multiple of 5 without using / and % operators in C++
- Check if a number is an Unusual Number or not in C++
- Check if a number is an Achilles number or not in C++
- Check if a number is an Achilles number or not in Python
- Check if a number is a power of another number in C++