Friday, December 27, 2024
Google search engine
HomeData Modelling & AIWrite an Efficient Method to Check if a Number is Multiple of...

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

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:  2^{4} * a  +  2^{3} * b  +  2^{2} * c  +  2^{1} * d  +  2^{0} * e

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:

2^{0} = 3 * 0 + 1 \\ 2^{1} = 3 * 1 - 1 \\ 2^{2} = 3 * 1 + 1 \\ 2^{3} = 3 * 3 - 1 ans so on...

Therefore, the decimal form becomes: 

(3n+1) * a  +  (3n-1) * b  +  (3n+1) * c  +  (3n-1) * d  +  (3n+1) * e [Tex](3n)(a+b+c+d+e) + (a - b + c - d + e) \\[/Tex](multiple of 3)+ (a + c + e) - (b + d) 

To have this number divisible by 3, the term (a + c + e) - (b + d)                                        should be divisible by 3. 

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>
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




// Java program to check if
// n is a multiple of 3
import 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


Python3




# Python program to check if n is a multiple of 3
 
# Function to check if n is a multiple of 3
def 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 isMultipleOf3
num = 24
if (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 3
using 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
// PHP program to check if n
// is a multiple of 3
 
 
// 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 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.
?>


Javascript




<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>


Output

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>
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;
}


C




// C program to check if n is a multiple of 3
#include <stdio.h>
#include<string.h>
 
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;
    }
   
  int abs = (odd_count - even_count);
  if(abs<0)
  {
    abs= -1*abs;
  }
 
    dp[n] = isMultipleOf3(abs);
     
    // 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;
}
 
// This code is contributed by akashish_.


Java




// 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


Python3




# Python program to check if n is a multiple of 3
dp = [-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#




// C# program to check if
// n is a multiple of 3
using 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 Code
public 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.


Javascript




<script>
// JavaScript program to check if n is a multiple of 3
let 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>


Output

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>
using namespace std;
 
int main()
{
    // input number
    int num = 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";
    }
    return 0;
}
 
// 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 not
import java.io.*;
import java.util.*;
  
class GFG
{
   
  public static void main(String[] args)
  {
    //input
   int  num = 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 number
num = 24
print(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 3
if (num % 3 is 0):
  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 division
using System;
 
public class GFG {
 
  static public void Main()
  {
 
    // input number
    int num = 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>


Output

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>
 
using namespace std;
 
bool is_multiple_of_3(int num) {
    // Calculate digital root
    while (num > 9) {
        string num_str = to_string(num);
        int sum = 0;
        for (int i = 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) {
        return true;
    } else {
        return false;
    }
}
 
int main() {
    cout << boolalpha << is_multiple_of_3(123) << endl;
    cout << boolalpha << is_multiple_of_3(789) << endl;
    return 0;
}


Java




public class GFG {
    public static boolean isMultipleOf3(int num)
    {
        // Calculate digital root
        while (num > 9) {
            int sum = 0;
            while (num > 0) {
                sum += num % 10;
                num /= 10;
            }
            num = sum;
        }
        // Check if digital root is 3, 6, or 9
        if (num % 3 == 0) {
            return true;
        }
        else {
            return false;
        }
    }
    public static void main(String[] args)
    {
        int num1 = 123;
        int num2 = 789;
        System.out.println(
            isMultipleOf3(num1)); // Output: true
        System.out.println(
            isMultipleOf3(num2)); // Output: true
    }
}


Python3




def is_multiple_of_3(num):
    # Calculate digital root
    while num > 9:
        num = sum(map(int, str(num)))
    # Check if digital root is 3, 6, or 9
    if num % 3 == 0:
        return True
    else:
        return False
 
print(is_multiple_of_3(123))
print(is_multiple_of_3(789))


C#




using System;
 
namespace IsMultipleOf3 {
    class Program {
        static bool IsMultipleOf3(int num) {
            // Calculate digital root
            while (num > 9) {
                int sum = 0;
                foreach (char c in num.ToString()) {
                    sum += c - '0';
                }
                num = sum;
            }
            // Check if digital root is 3, 6, or 9
            if (num % 3 == 0) {
                return true;
            } else {
                return false;
            }
        }
 
        static void Main(string[] args) {
            Console.WriteLine(IsMultipleOf3(123));
            Console.WriteLine(IsMultipleOf3(789));
        }
    }
}


Javascript




function is_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) {
        return true;
    } else {
        return false;
    }
}
 
console.log(is_multiple_of_3(123));
console.log(is_multiple_of_3(789));


Output

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
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments