The very first solution that comes to our mind is the one that we learned in school. If the sum of digits in a number is a multiple of 3 then the number is a multiple of 3, e.g., for 612, the sum of digits is 9 so it’s a multiple of 3. But this solution is not efficient. You have to get all decimal digits one by one, add them and then check if the sum is a multiple of 3.
 
There is a pattern in the binary representation of a number that can be used to find if a number is a multiple of 3. If the difference between the count of odd set bits (Bits set at odd positions) and even set bits is a multiple of 3 then is the number.
Example: 23 (00..10111) 
1) Get count of all set bits at odd positions (For 23 it’s 3). 
2) Get count of all set bits at even positions (For 23 it’s 1). 
3) If the difference between the above two counts is a multiple of 3 then the number is also a multiple of 3. 
(For 23 it’s 2 so 23, is not a multiple of 3)
Take some more examples like 21, 15, etc…
 
Algorithm: isMutlipleOf3(n)
1) Make n positive if n is negative.
2) If number is 0 then return 1
3) If number is 1 then return 0
4) Initialize: odd_count = 0, even_count = 0
5) Loop while n != 0
    a) If rightmost bit is set then increment odd count.
    b) Right-shift n by 1 bit
    c) If rightmost bit is set then increment even count.
    d) Right-shift n by 1 bit
6) return isMutlipleOf3(odd_count - even_count)
Proof:
Let the binary representation of the number be: abcde.
In decimal form this number will be:  
Every even power of 2 can be represented as 3n + 1, and every odd power of 2 can be represented as 3n – 1. For example:
ans so on...
Therefore, the decimal form becomes:
[Tex](3n)(a+b+c+d+e) + (a - b + c - d + e) \\[/Tex](multiple of 3)
To have this number divisible by 3, the term 
Therefore for the number to be divisible by, the difference between the count of odd set bits (a + c + e) and even set bits (b + d) should be divisible by 3.
Program:
C++
| // CPP program to check if n is a multiple of 3#include <bits/stdc++.h>usingnamespacestd;/* Function to check if n is a multiple of 3*/intisMultipleOf3(intn){    intodd_count = 0;    inteven_count = 0;    /* Make no positive if +n is multiple of 3    then is -n. We are doing this to avoid    stack overflow in recursion*/    if(n < 0)        n = -n;    if(n == 0)        return1;    if(n == 1)        return0;    while(n) {        /* If odd bit is set then        increment odd counter */        if(n & 1)            odd_count++;        /* If even bit is set then        increment even counter */        if(n & 2)            even_count++;        n = n >> 2;    }    returnisMultipleOf3(abs(odd_count - even_count));}/* Program to test function isMultipleOf3 */intmain(){    intnum = 24;    if(isMultipleOf3(num))        printf("%d is multiple of 3", num);    else        printf("%d is not a multiple of 3", num);    return0;} | 
Java
| // Java program to check if// n is a multiple of 3importjava.lang.*;importjava.util.*;classGFG {    // Function to check if n    // is a multiple of 3    staticintisMultipleOf3(intn)    {        intodd_count = 0;        inteven_count = 0;        /* Make no positive if +n is multiple     of 3 then is -n. We are doing this to     avoid stack overflow in recursion*/        if(n < 0)            n = -n;        if(n == 0)            return1;        if(n == 1)            return0;        while(n != 0) {            /* If odd bit is set then        increment odd counter */            if((n & 1) != 0)                odd_count++;            /* If even bit is set then        increment even counter */            if((n & 2) != 0)                even_count++;            n = n >> 2;        }        returnisMultipleOf3(Math.abs(odd_count - even_count));    }    /* Program to test function isMultipleOf3 */    publicstaticvoidmain(String[] args)    {        intnum = 24;        if(isMultipleOf3(num) != 0)            System.out.println(num + " is multiple of 3");        else            System.out.println(num + " is not a multiple of 3");    }}// This code is contributed by Sahil_Bansall | 
Python3
| # Python program to check if n is a multiple of 3# Function to check if n is a multiple of 3defisMultipleOf3(n):    odd_count =0    even_count =0    # Make no positive if + n is multiple of 3    # then is -n. We are doing this to avoid    # stack overflow in recursion    if(n < 0):         n =-n    if(n ==0):        return1    if(n ==1):         return0    while(n):                # If odd bit is set then        # increment odd counter         if(n & 1):             odd_count +=1        # If even bit is set then        # increment even counter         if(n & 2):            even_count +=1        n =n >> 2    returnisMultipleOf3(abs(odd_count -even_count))# Program to test function isMultipleOf3 num =24if(isMultipleOf3(num)):     print(num, 'is multiple of 3')else:    print(num, 'is not a multiple of 3')# This code is contributed by Danish Raza | 
C#
| // C# program to check if// n is a multiple of 3usingSystem;classGFG {    // Function to check if n    // is a multiple of 3    staticintisMultipleOf3(intn)    {        intodd_count = 0, even_count = 0;        /* Make no positive if +n is multiple         of 3 then is -n. We are doing this to         avoid stack overflow in recursion*/        if(n < 0)            n = -n;        if(n == 0)            return1;        if(n == 1)            return0;        while(n != 0) {            /* If odd bit is set then            increment odd counter */            if((n & 1) != 0)                odd_count++;            /* If even bit is set then            increment even counter */            if((n & 2) != 0)                even_count++;            n = n >> 2;        }        returnisMultipleOf3(Math.Abs(odd_count - even_count));    }    // Driver Code    publicstaticvoidMain()    {        intnum = 24;        if(isMultipleOf3(num) != 0)            Console.Write(num + " is multiple of 3");        else            Console.Write(num + " is not a multiple of 3");    }}// This code is contributed by Sam007 | 
PHP
| <?php// PHP program to check if n// is a multiple of 3// Function to check if n // is a multiple of 3functionisMultipleOf3( $n){    $odd_count= 0;    $even_count= 0;    // Make no positive if +n     // is multiple of 3 then is -n.     // We are doing this to avoid    // stack overflow in recursion    if($n< 0) $n= -$n;    if($n== 0) return1;    if($n== 1) return0;    while($n)    {        // If odd bit is set then        // increment odd counter         if($n& 1)         $odd_count++;        // If even bit is set then        // increment even counter        if($n& 2)            $even_count++;        $n= $n>> 2;    }    returnisMultipleOf3(abs($odd_count-                              $even_count));}// Driver Code$num= 24;if(isMultipleOf3($num))     echo$num, "is multiple of 3";else    echo$num, "is not a multiple of 3";    // This code is contributed by vt_m.?> | 
Javascript
| <script>/*Function to check if n is a multiple of 3*/    functionisMultipleof3(n)    {        odd_count = 0;        even_count = 0;                /* Make no positive if +n is multiple of 3        then is -n. We are doing this to avoid        stack overflowin recursion*/                if(n < 0)        n = -n;        if(n == 0)        return1;        if(n == 1)        return0;                 while(n)          {             /*If odd bit is set then              increment odd counter*/             if(n & 1)             odd_count++;                          /*If even bit is set then              increment even counter*/             if(n & 2)             even_count++;             n = n>>2;         }         returnisMultipleof3(Math.abs(odd_count-even_count));    }                 /*Program to test function isMultipleof3*/          num = 24;          if(isMultipleof3(num))             document.write(num + " is multiple of 3");          else             document.write(num + " is not a multiple of 3");              // This code is contributed by simranarora5sos  </script> | 
24 is multiple of 3
Time Complexity: O(logn)
Auxiliary Space: O(1)
Efficient Method: 
Use Dynamic Programming (Top-Down Approach Using Memoization)
C++
| // CPP program to check if n is a multiple of 3#include <bits/stdc++.h>usingnamespacestd;intstaticdp[1001];/* Function to check if n is a multiple of 3*/intisMultipleOf3(intn){    intodd_count = 0;    inteven_count = 0;        // Base Cases    if(n < 0)        n = -n;            if(n == 0)        return1;            if(n == 1)        return0;        // If a value is already present    // in dp, return it    if(dp[n] != -1)        returndp[n];        while(n) {        /* If odd bit is set then        increment odd counter */        if(n & 1)            odd_count++;        /* If even bit is set then        increment even counter */        if(n & 2)            even_count++;        n = n >> 2;    }    dp[n] = isMultipleOf3(abs(odd_count - even_count));        // return dp    returndp[n];}/* Program to test function isMultipleOf3 */intmain(){    intnum = 24;        memset(dp, -1, sizeof(dp));        if(isMultipleOf3(num))        printf("%d is multiple of 3", num);    else        printf("%d is not a multiple of 3", num);    return0;} | 
C
| // C program to check if n is a multiple of 3#include <stdio.h>#include<string.h>intstaticdp[1001];/* Function to check if n is a multiple of 3*/intisMultipleOf3(intn){    intodd_count = 0;    inteven_count = 0;        // Base Cases    if(n < 0)        n = -n;            if(n == 0)        return1;            if(n == 1)        return0;        // If a value is already present    // in dp, return it    if(dp[n] != -1)        returndp[n];        while(n) {        /* If odd bit is set then        increment odd counter */        if(n & 1)            odd_count++;        /* If even bit is set then        increment even counter */        if(n & 2)            even_count++;        n = n >> 2;    }    intabs= (odd_count - even_count);  if(abs<0)  {    abs= -1*abs;  }    dp[n] = isMultipleOf3(abs);        // return dp    returndp[n];}/* Program to test function isMultipleOf3 */intmain(){    intnum = 24;        memset(dp, -1, sizeof(dp));        if(isMultipleOf3(num))        printf("%d is multiple of 3", num);    else        printf("%d is not a multiple of 3", num);    return0;}// This code is contributed by akashish_. | 
Java
| // JAVA program to check if n is a multiple of 3importjava.util.*;classGFG{ staticint[]dp ;/* Function to check if n is a multiple of 3*/staticintisMultipleOf3(intn){    intodd_count = 0;    inteven_count = 0;        // Base Cases    if(n < 0)        n = -n;            if(n == 0)        return1;            if(n == 1)    return0;        // If a value is already present    // in dp, return it    if(dp[n] != -1)        returndp[n];        while(n > 0) {        /* If odd bit is set then        increment odd counter */        if((n & 1) != 0)            odd_count++;         /* If even bit is set then        increment even counter */        if((n & 2) != 0)            even_count++;        n = n >> 2;    }    dp[n] = isMultipleOf3(Math.abs(odd_count - even_count));        // return dp    returndp[n];}/* Program to test function isMultipleOf3 */publicstaticvoidmain(String[] args){    intnum = 24;    dp = newint[1001];    Arrays.fill(dp, -1);        if(isMultipleOf3(num) == 1)        System.out.printf("%d is multiple of 3", num);    else        System.out.printf("%d is not a multiple of 3", num);}}// This codeiscontributed by Rajput-Ji | 
Python3
| # Python program to check if n is a multiple of 3dp =[-1fori inrange(1001)];''' Function to check if n is a multiple of 3 '''defisMultipleOf3(n):    odd_count =0;    even_count =0;    # Base Cases    if(n < 0):        n =-n;    if(n ==0):        return1;    if(n ==1):        return0;    # If a value is already present    # in dp, return it    if(dp[n] !=-1):        returndp[n];    while(n > 0):        '''         * If odd bit is set then increment odd counter         '''        if((n & 1) !=0):            odd_count+=1;        '''         * If even bit is set then increment even counter         '''        if((n & 2) !=0):            even_count+=1;        n =n >> 2;        dp[n] =isMultipleOf3(abs(odd_count -even_count));    # return dp    returndp[n];''' Program to test function isMultipleOf3 '''if__name__ =='__main__':    num =24;    if(isMultipleOf3(num) ==1):        print(num,"is multiple of 3");    else:        print(num," is not a multiple of 3");# This code is contributed by Rajput-Ji  | 
C#
| // C# program to check if// n is a multiple of 3usingSystem;classGFG {    staticint[]dp = newint[1001]; /* Function to check if n is a multiple of 3*/staticintisMultipleOf3(intn){    intodd_count = 0;    inteven_count = 0;         // Base Cases    if(n < 0)        n = -n;             if(n == 0)        return1;             if(n == 1)        return0;         // If a value is already present    // in dp, return it    if(dp[n] != -1)        returndp[n];         while(n > 0) {        /* If odd bit is set then        increment odd counter */        if((n & 1) != 0)            odd_count++;         /* If even bit is set then        increment even counter */        if((n & 2) != 0)            even_count++;        n = n >> 2;    }     dp[n] = isMultipleOf3(Math.Abs(odd_count - even_count));         // return dp    returndp[n];}    // Driver CodepublicstaticvoidMain(){   intnum = 24;         for(inti = 0; i < 1001; i++) {        dp[i] = -1;    }         if(isMultipleOf3(num) == 1)        Console.Write(num + " is multiple of 3");    else        Console.Write(num + " is not a multiple of 3");}}// This code is contributed by Samim Hossain Mondal. | 
Javascript
| <script>// JavaScript program to check if n is a multiple of 3let dp = [];for(let i = 0; i < 1001; i++) {    dp[i] = -1;}/* Function to check if n is a multiple of 3*/functionisMultipleOf3(n){    let odd_count = 0;    let even_count = 0;        // Base Cases    if(n < 0)        n = -n;            if(n == 0)        return1;            if(n == 1)        return0;        // If a value is already present    // in dp, return it    if(dp[n] != -1)        returndp[n];        while(n) {        /* If odd bit is set then        increment odd counter */        if(n & 1)            odd_count++;        /* If even bit is set then        increment even counter */        if(n & 2)            even_count++;        n = n >> 2;    }    dp[n] = isMultipleOf3(Math.abs(odd_count - even_count));        // return dp    returndp[n];}/* Program to test function isMultipleOf3 */let num = 24;    if(isMultipleOf3(num))    document.write(num + " is multiple of 3");else    document.write(num + " is not a multiple of 3");// This code is contributed by Samim Hossain Mondal.</script> | 
24 is multiple of 3
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Method: Checking given number is multiple of 3 or not using modulo division.
C++
| // C++ program to check if given number is multiple of 3 or// not using modulo division#include <iostream>usingnamespacestd;intmain(){    // input number    intnum = 24;    cout << num;    // checking if the given number if multiple of 3 or not    // using modulo division operator if the output of num%3    // is equal to 0 then it is considered as multiple of 3    // otherwise not a multiple of 3    if(num % 3 == 0) {        cout << " is multiple of 3";    }    else{        cout << " is not multiple of 3";    }    return0;}// this code is contributed by gangarajula laxmi | 
Java
| /*package whatever //do not write package name here */// Java code// To check whether the given number is divisible by 3 or notimportjava.io.*;importjava.util.*;  classGFG{    publicstaticvoidmain(String[] args)  {    //input   intnum = 24;    System.out.println(num);        /// checking if the given number if multiple of 3 or not    // using modulo division operator if the output of num%3    // is equal to 0 then it is considered as multiple of 3    // otherwise not a multiple of 3    if((n) % 3== 0)    {        System.out.println(" is multiple of 3");    }    else    {        System.out.println(" is not multiple of 3");    }   }}// This code is contributed by satwik4409. | 
Python3
| # Python3 program to check if given number is multiple of 3 or# not using modulo division# input numbernum =24print(num,end="")# checking if the given number if multiple of 3 or not# using modulo division operator if the output of num%3# is equal to 0 then it is considered as multiple of 3# otherwise not a multiple of 3if(num %3is0):  print(" is multiple of 3")else:  print( " is not multiple of 3")# This code is contributed by akashish__ | 
C#
| // C# program to check if given number is multiple of 3 or// not using modulo divisionusingSystem;publicclassGFG {  staticpublicvoidMain()  {    // input number    intnum = 24;    // checking if the given number if multiple of 3 or    // not using modulo division operator if the output    // of num%3 is equal to 0 then it is considered as    // multiple of 3 otherwise not a multiple of 3    if(num % 3 == 0) {      Console.WriteLine(num+" is multiple of 3");    }    else{      Console.WriteLine(num+" is not multiple of 3");    }  }}// This code is contributed by laxmigangarajula03 | 
Javascript
| <script>       // JavaScript code for the above approach       // input number       let num = 24;       document.write(num);       // checking if the given number if multiple of 3 or not       // using modulo division operator if the output of num%3       // is equal to 0 then it is considered as multiple of 3       // otherwise not a multiple of 3       if(num % 3 == 0) {           document.write(" is multiple of 3");       }       else{           document.write(" is not multiple of 3");       }   // This code is contributed by Potta Lokesh   </script> | 
24 is multiple of 3
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 4:
1. It takes a number ‘num’ as input.
2. It calculates the digital root of the number by repeatedly adding the digits of the number until it becomes a single-digit number.
3. It then checks if the digital root is 3, 6, or 9, and returns True if it is, and False otherwise.
For example, for the number 123, the digital root would be calculated as follows:
1 + 2 + 3 = 6
Since 6 is divisible by 3, the function will return True for the input 123.
C++
| #include <iostream>#include <string>usingnamespacestd;boolis_multiple_of_3(intnum) {    // Calculate digital root    while(num > 9) {        string num_str = to_string(num);        intsum = 0;        for(inti = 0; i < num_str.length(); i++) {            sum += num_str[i] - '0';        }        num = sum;    }    // Check if digital root is 3, 6, or 9    if(num % 3 == 0) {        returntrue;    } else{        returnfalse;    }}intmain() {    cout << boolalpha << is_multiple_of_3(123) << endl;    cout << boolalpha << is_multiple_of_3(789) << endl;    return0;} | 
Java
| publicclassGFG {    publicstaticbooleanisMultipleOf3(intnum)    {        // Calculate digital root        while(num > 9) {            intsum = 0;            while(num > 0) {                sum += num % 10;                num /= 10;            }            num = sum;        }        // Check if digital root is 3, 6, or 9        if(num % 3== 0) {            returntrue;        }        else{            returnfalse;        }    }    publicstaticvoidmain(String[] args)    {        intnum1 = 123;        intnum2 = 789;        System.out.println(            isMultipleOf3(num1)); // Output: true        System.out.println(            isMultipleOf3(num2)); // Output: true    }} | 
Python3
| defis_multiple_of_3(num):    # Calculate digital root    whilenum > 9:        num =sum(map(int, str(num)))    # Check if digital root is 3, 6, or 9    ifnum %3==0:        returnTrue    else:        returnFalseprint(is_multiple_of_3(123))print(is_multiple_of_3(789)) | 
C#
| usingSystem;namespaceIsMultipleOf3 {    classProgram {        staticboolIsMultipleOf3(intnum) {            // Calculate digital root            while(num > 9) {                intsum = 0;                foreach(charc innum.ToString()) {                    sum += c - '0';                }                num = sum;            }            // Check if digital root is 3, 6, or 9            if(num % 3 == 0) {                returntrue;            } else{                returnfalse;            }        }        staticvoidMain(string[] args) {            Console.WriteLine(IsMultipleOf3(123));            Console.WriteLine(IsMultipleOf3(789));        }    }} | 
Javascript
| functionis_multiple_of_3(num) {    // Calculate digital root    while(num > 9) {        let num_str = num.toString();        let sum = 0;        for(let i = 0; i < num_str.length; i++) {            sum += parseInt(num_str[i]);        }        num = sum;    }    // Check if digital root is 3, 6, or 9    if(num % 3 === 0) {        returntrue;    } else{        returnfalse;    }}console.log(is_multiple_of_3(123));console.log(is_multiple_of_3(789)); | 
True True
Time complexity: O(log n), where n is the input value
Auxiliary Space: O(1)
Related Articles: 
Check divisibility in a binary stream 
DFA based division
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
 
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







