Write an Efficient Method to Check if a Number is Multiple of 3 - GeeksforGeeks

23 Mar, 2022
The very first solution that comes to our mind is the one that we learned in school. If sum of digits in a number is multiple of 3 then number is multiple of 3 e.g., for 612 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 sum is multiple of 3. 
There is a pattern in binary representation of the number that can be used to find if number is a multiple of 3. If difference between count of odd set bits (Bits set at odd positions) and even set bits is 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 difference of above two counts is a multiple of 3 then 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: Above can be proved by taking the example of 11 in decimal numbers. (In this context 11 in decimal numbers is same as 3 in binary numbers) If difference between sum of odd digits and even digits is multiple of 11 then decimal number is multiple of 11. Let’s see how.Let’s take the example of 2 digit numbers in decimal AB = 11A -A + B = 11A + (B – A) So if (B – A) is a multiple of 11 then is AB.Let us take 3 digit numbers.ABC = 99A + A + 11B – B + C = (99A + 11B) + (A + C – B) So if (A + C – B) is a multiple of 11 then is (ABC)Let us take 4 digit numbers now. ABCD = 1001A + D + 11C – C + 999B + B – A = (1001A – 999B + 11C) + (D + B – A -C ) So, if (B + D – A – C) is a multiple of 11 then is ABCD.This can be continued for all decimal numbers. Above concept can be proved for 3 in binary numbers in the same way. Time Complexity: O(logn)Program:  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to check if n is a multiple of 3#include <bits/stdc++.h>using namespace std; /* Function to check if n is a multiple of 3*/int isMultipleOf3(int n){    int odd_count = 0;    int 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)        return 1;    if (n == 1)        return 0;     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;    }     return isMultipleOf3(abs(odd_count - even_count));} /* Program to test function isMultipleOf3 */int main(){    int num = 24;    if (isMultipleOf3(num))        printf("%d is multiple of 3", num);    else        printf("%d is not a multiple of 3", num);    return 0;}
// Java program to check if// n is a multiple of 3import java.lang.*;import java.util.*; class GFG {    // Function to check if n    // is a multiple of 3    static int isMultipleOf3(int n)    {        int odd_count = 0;        int 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)            return 1;        if (n == 1)            return 0;         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;        }         return isMultipleOf3(Math.abs(odd_count - even_count));    }     /* Program to test function isMultipleOf3 */    public static void main(String[] args)    {        int num = 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
# Python program to check if n is a multiple of 3 # Function to check if n is a multiple of 3def isMultipleOf3(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):        return 1    if(n == 1):        return 0     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     return isMultipleOf3(abs(odd_count - even_count)) # Program to test function isMultipleOf3num = 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# program to check if// n is a multiple of 3using System; class GFG {     // Function to check if n    // is a multiple of 3    static int isMultipleOf3(int n)    {        int 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)            return 1;        if (n == 1)            return 0;         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;        }         return isMultipleOf3(Math.Abs(odd_count - even_count));    }     // Driver Code    public static void Main()    {        int num = 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 program to check if n// is a multiple of 3  // Function to check if n// is a multiple of 3function isMultipleOf3( $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) return 1;    if($n == 1) return 0;     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;    }     return isMultipleOf3(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.?>
<script>/*Function to check if n is a multiple of 3*/    function isMultipleof3(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)        return 1;        if(n == 1)        return 0;                  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;         }         return isMultipleof3(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
Efficient Method: 
Use Dynamic Programming (Top-Down Approach Using Memoization)
C++
Java
Python3
C#
Javascript
// CPP program to check if n is a multiple of 3#include <bits/stdc++.h>using namespace std; int static dp[1001]; /* Function to check if n is a multiple of 3*/int isMultipleOf3(int n){    int odd_count = 0;    int even_count = 0;         // Base Cases    if (n < 0)        n = -n;             if (n == 0)        return 1;             if (n == 1)        return 0;         // If a value is already present    // in dp, return it    if(dp[n] != -1)        return dp[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    return dp[n];} /* Program to test function isMultipleOf3 */int main(){    int num = 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);    return 0;}
// JAVA program to check if n is a multiple of 3 import java.util.*; class GFG{  static int []dp ; /* Function to check if n is a multiple of 3*/static int isMultipleOf3(int n){    int odd_count = 0;    int even_count = 0;         // Base Cases    if (n < 0)        n = -n;             if (n == 0)        return 1;             if (n == 1)    return 0;         // If a value is already present    // in dp, return it    if(dp[n] != -1)        return dp[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    return dp[n];} /* Program to test function isMultipleOf3 */public static void main(String[] args){    int num = 24;    dp = new int[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
# Python program to check if n is a multiple of 3dp = [-1 for i in range(1001)]; ''' Function to check if n is a multiple of 3 '''def isMultipleOf3(n):    odd_count = 0;    even_count = 0;     # Base Cases    if (n < 0):        n = -n;     if (n == 0):        return 1;     if (n == 1):        return 0;     # If a value is already present    # in dp, return it    if (dp[n] != -1):        return dp[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    return dp[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# program to check if// n is a multiple of 3using System; class GFG {     static int []dp = new int[1001];  /* Function to check if n is a multiple of 3*/static int isMultipleOf3(int n){    int odd_count = 0;    int even_count = 0;          // Base Cases    if (n < 0)        n = -n;              if (n == 0)        return 1;              if (n == 1)        return 0;          // If a value is already present    // in dp, return it    if(dp[n] != -1)        return dp[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    return dp[n];}     // Driver Codepublic static void Main(){   int num = 24;          for(int i = 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.
<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*/function isMultipleOf3(n){    let odd_count = 0;    let even_count = 0;         // Base Cases    if (n < 0)        n = -n;             if (n == 0)        return 1;             if (n == 1)        return 0;         // If a value is already present    // in dp, return it    if(dp[n] != -1)        return dp[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    return dp[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(n)
Auxiliary Space: O(n)
YouTubeGeeksforGeeks500K subscribersWrite an Efficient Method to Check if a Number is Multiple of 3 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:05•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=HcD4CQprpB8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Related Articles: Check divisibility in a binary stream DFA based divisionPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
Deepak Koli
vt_m
q123
simranarora5sos
sagartomar9927
samim2000
Rajput-Ji
Amazon
Microsoft
Bit Magic
Mathematical
Amazon
Microsoft
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Cyclic Redundancy Check and Modulo-2 Division
Count set bits in an integer
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
Prime Numbers
Merge two sorted arrays