Largest number with the given set of N digits that is divisible by 2, 3 and 5

Given a set of ‘N’ digits. The task is to find the maximum integer that we can make from these digits. The resultant number must be divisible by 2, 3 and 5.
Note: It is not necessary to use all the digits from the set. Also, leading zeroes are not allowed.

Examples:

Input: N = 11, setOfDigits = {3, 4, 5, 4, 5, 3, 5, 3, 4, 4, 0}
Output: 5554443330
After arranging all the elements in a non-increasing order as 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 0. The sum of all the digit is 40. Thus when we found out that the remainder of 40, when divided by 3, is 1. Then we’ll start traversing from the end to the start and if we encounter any digit with the same remainder, which we got 4 at the position 7 will be erased it. Now the sum is 36 which is divisible 3 and the new largest number will be 5554443330, which is divisible by 2, 3 and 5.

Input: N = 1, setOfDigits = {0}
Output: 0



Approach: Below is the step by step algorithm to solve this problem:

  1. Initialize the set of digits in a vector.
  2. Any number is divisible by 2, 3 and 5 only if the sum of digits is divisible by 3 and the last digit is 0.
  3. Check if 0 is not present in the vector, then it is not possible to create a number because it will not be divisible by 5.
  4. Sort the vector in a non-increasing manner if the first element is 0 after that, then print 0.
  5. Find the modulus of sum of all the digits by 3 and if it’s 1 then delete the first element with the same remainder while traversing from the end.
  6. If there is no element with the same remainder, then delete two elements which has a remainder as 3 – y.
  7. Print all the remaining digits of a vector as a single integer.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long
  
// Function to find the largest
// integer with the given set
int findLargest(int n, vector<int> &v)
{
  
    int flag = 0;
    ll sum = 0;
  
    // find sum of all the digits
    // look if any 0 is present or not
    for (int i = 0; i < n; i++) {
        if (v[i] == 0)
            flag = 1;
        sum += v[i];
    }
  
    // if 0 is not present, the resultant number
    // won't be divisible by 5
    if (!flag)
        cout << "Not possible" << endl;
  
    else {
        // sort all the elements in a non-decreasing manner
        sort(v.begin(), v.end(), greater<int>());
  
        // if there is just one element 0
        if (v[0] == 0) {
            cout << "0" << endl;
            return 0;
        }
        else {
            int flag = 0;
  
            // find the remainder of the sum
            // of digits when divided by 3
            int y = sum % 3;
  
            // there can a remainder as 1 or 2
            if (y != 0) {
  
                // traverse from the end of the digits
                for (int i = n - 1; i >= 0; i--) {
  
                    // first element which has the same remainder
                    // remove it
                    if (v[i] % 3 == y) {
                        v.erase(v.begin() + i);
                        flag = 1;
                        break;
                    }
                }
                // if there is no element which
                // has a same remainder as y
                if (flag == 0) {
  
                    // subtract it by 3 ( could be one or two)
                    y = 3 - y;
  
                    int cnt = 0;
                    for (int i = n - 1; i >= 0; i--) {
  
                        // delete two minimal digits
                        // which has a remainder as y
                        if (v[i] % 3 == y) {
                            v.erase(v.begin() + i);
                            cnt++;
  
                            if (cnt >= 2)
                                break;
                        }
                    }
                }
            }
            if (*v.begin() == 0)
                cout << "0" << endl;
  
            // print all the digits as a single integer
            else
                for (int i : v) {
                    cout << i;
                }
        }
    }
}
  
// Driver code
int main()
{
    // initialize the number of set of digits
    int n = 11;
  
    // initialize all the set of digits in a vector
    vector<int> v{ 3, 9, 9, 6, 4, 3, 6, 4, 9, 6, 0 };
  
    findLargest(n, v);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of above approach
import java.util.*;
  
class GFG {
  
// Function to find the largest
// integer with the given set
static int findLargest(int n, Vector<Integer> v)
{
  
    int flag = 0;
    long sum = 0;
  
    // find sum of all the digits
    // look if any 0 is present or not
    for (int i = 0; i < n; i++) 
    {
        if (v.get(i) == 0)
            flag = 1;
        sum += v.get(i);
    }
  
    // if 0 is not present, the resultant number
    // won't be divisible by 5
    if (flag != 1)
        System.out.println("Not possible");
  
    else 
    {
        // sort all the elements in a non-decreasing manner
        Collections.sort(v,Collections.reverseOrder());
  
        // if there is just one element 0
        if (v.get(0) == 0)
        {
            System.out.println("0");
            return 0;
        }
        else 
        {
            int flags = 0;
  
            // find the remainder of the sum
            // of digits when divided by 3
            int y = (int) (sum % 3);
  
            // there can a remainder as 1 or 2
            if (y != 0
            {
  
                // traverse from the end of the digits
                for (int i = n - 1; i >= 0; i--) 
                {
  
                    // first element which has the same remainder
                    // remove it
                    if (v.get(i) % 3 == y) 
                    {
                        v.remove(i);
                        flags = 1;
                        break;
                    }
                }
                  
                // if there is no element which
                // has a same remainder as y
                if (flags == 0
                {
  
                    // subtract it by 3 ( could be one or two)
                    y = 3 - y;
  
                    int cnt = 0;
                    for (int i = n - 1; i >= 0; i--)
                    {
  
                        // delete two minimal digits
                        // which has a remainder as y
                        if (v.get(i) % 3 == y) 
                        {
                            v.remove(i);
                            cnt++;
  
                            if (cnt >= 2)
                                break;
                        }
                    }
                }
            }
            if (v.get(0) == 0)
                System.out.println("0");
  
            // print all the digits as a single integer
            else
                for (Integer i : v) 
                {
                    System.out.print(i);
                }
        }
    }
    return Integer.MIN_VALUE;
}
  
// Driver code
public static void main(String[] args) 
{
    // initialize the number of set of digits
    int arr[] = { 3, 9, 9, 6, 4, 3, 6, 4, 9, 6, 0 };
    int n = 11;
      
    Vector<Integer> v = new Vector<Integer> ();
      
    // initialize all the set of digits in a vector
    for(int i = 0; i < n; i++)
        v.add(i, arr[i]);
  
    findLargest(n, v);
}
}
  
// This code contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of above approach
  
# Function to find the largest
# integer with the given set
def findLargest(n, v):
    flag = 0
    sum = 0
      
    # find sum of all the digits
    # look if any 0 is present or not
    for i in range(n):
        if (v[i] == 0):
            flag = 1
        sum += v[i]
  
    # if 0 is not present, the resultant number
    # won't be divisible by 5
    if (flag == 0):
        print("Not possible")
  
    else:
          
        # sort all the elements in a 
        # non-decreasing manner
        v.sort(reverse = True)
  
        # if there is just one element 0
        if (v[0] == 0):
            print("0")
            return 0
          
        else:
            flag = 0
  
            # find the remainder of the sum
            # of digits when divided by 3
            y = sum % 3
  
            # there can a remainder as 1 or 2
            if (y != 0):
                  
                # traverse from the end of the digits
                i = n - 1
                while(i >= 0):
                      
                    # first element which has the same 
                    # remainder, remove it
                    if (v[i] % 3 == y):
                        v.remove(v[i])
                        flag = 1
                        break
                    i -= 1
                  
                # if there is no element which
                # has a same remainder as y
                if (flag == 0):
                      
                    # subtract it by 3 ( could be one or two)
                    y = 3 - y
  
                    cnt = 0
                    i = n - 1
                    while(i >= 0):
                          
                        # delete two minimal digits
                        # which has a remainder as y
                        if (v[i] % 3 == y):
                            v.remove(v[i])
                            cnt += 1
  
                            if (cnt >= 2):
                                break
                          
                        i -= 1
                  
            if (v[0] == 0):
                print("0")
  
            # print all the digits as a single integer
            else:
                for i in (v):
                    print(i, end = "")
          
# Driver code
if __name__ == '__main__':
      
    # initialize the number of set of digits
    n = 11
  
    # initialize all the set of 
    # digits in a vector
    v = [3, 9, 9, 6, 4, 3,
            6, 4, 9, 6, 0]
  
    findLargest(n, v)
      
# This code is contributed by
# Surendra_Gangwar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of above approach
using System;
using System.Collections;
  
class GFG 
{
  
// Function to find the largest
// integer with the given set
static int findLargest(int n, ArrayList v)
{
  
    int flag = 0;
    long sum = 0;
  
    // find sum of all the digits
    // look if any 0 is present or not
    for (int i = 0; i < n; i++) 
    {
        if ((int)v[i] == 0)
            flag = 1;
        sum += (int)v[i];
    }
  
    // if 0 is not present, the resultant number
    // won't be divisible by 5
    if (flag != 1)
        Console.WriteLine("Not possible");
  
    else
    {
        // sort all the elements in a non-decreasing manner
        v.Sort();
        v.Reverse();
  
        // if there is just one element 0
        if ((int)v[0] == 0)
        {
            Console.WriteLine("0");
            return 0;
        }
        else
        {
            int flags = 0;
  
            // find the remainder of the sum
            // of digits when divided by 3
            int y = (int) (sum % 3);
  
            // there can a remainder as 1 or 2
            if (y != 0) 
            {
  
                // traverse from the end of the digits
                for (int i = n - 1; i >= 0; i--) 
                {
  
                    // first element which has the same remainder
                    // remove it
                    if ((int)v[i] % 3 == y) 
                    {
                        v.RemoveAt(i);
                        flags = 1;
                        break;
                    }
                }
                  
                // if there is no element which
                // has a same remainder as y
                if (flags == 0) 
                {
  
                    // subtract it by 3 ( could be one or two)
                    y = 3 - y;
  
                    int cnt = 0;
                    for (int i = n - 1; i >= 0; i--)
                    {
  
                        // delete two minimal digits
                        // which has a remainder as y
                        if ((int)v[i] % 3 == y) 
                        {
                            v.RemoveAt(i);
                            cnt++;
  
                            if (cnt >= 2)
                                break;
                        }
                    }
                }
            }
            if ((int)v[0] == 0)
                Console.WriteLine("0");
  
            // print all the digits as a single integer
            else
                for (int i = 0; i < v.Count; i++) 
                {
                    Console.Write(v[i]);
                }
        }
    }
    return int.MinValue;
}
  
// Driver code
static void Main() 
{
    // initialize the number of set of digits
    int []arr = { 3, 9, 9, 6, 4, 3, 6, 4, 9, 6, 0 };
    int n = 11;
      
    ArrayList v = new ArrayList();
      
    // initialize all the set of digits in a vector
    for(int i = 0; i < n; i++)
        v.Add(arr[i]);
  
    findLargest(n, v);
}
}
  
// This code contributed by mits

chevron_right


Output:

999666330


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.