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

 Live Demo

#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

Updated on: 17-Apr-2020

902 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements