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

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the largest number formed from the array that is divisible by 2, 3, and 5.

Let's see the steps to solve the problem.

  • Initialise the array.
  • The number must end with 0 and the sum of all the numbers should be divisible by 3 to be divisible by 2, 3, and 5.
  • Check for the 0 in the array and print not possible if it's not present in the array.
  • Sort the array in descending order.
  • Find the remainder for sum % 3.
  • If the remainder is not 1, then delete all the digits from the end whose remainder for digit % 3 is equal to the above remainder.
  • If there are no digits with the same remainder as above, then subtract 3 from the above remainder and delete the last two digits whose remainder is the same as above.
  • Print all the digits from the array.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void findLargestDivibleNumber(int n, vector<int>& v){
   int flag = 0;
   long long sum = 0;
   for (int i = 0; i < n; i++) {
      if (v[i] == 0) {
         flag = 1;
      }
      sum += v[i];
   }
   if (!flag) {
      cout << "Not possible" << endl;
   }else {
      sort(v.begin(), v.end(), greater<int>());
      if (v[0] == 0) {
         cout << "0" << endl;
      }else {
         int flag = 0;
         int remainder = sum % 3;
         if (remainder != 0) {
            for (int i = n - 1; i >= 0; i--) {
               if (v[i] % 3 == remainder) {
                  v.erase(v.begin() + i);
                  flag = 1;
                  break;
               }
            }
            if (flag == 0) {
               remainder = 3 - remainder;
               int count = 0;
               for (int i = n - 1; i >= 0; i--) {
                  if (v[i] % 3 == remainder) {
                     v.erase(v.begin() + i);
                     count++;
                     if (count >= 2) {
                        break;
                     }
                  }
               }
            }
         }
         if (*v.begin() == 0) {
            cout << "0" << endl;
         }else {
            for (int i : v) {
               cout << i;
            }
         }
      }
   }
}
int main() {
   int n = 9;
   vector<int> v{ 4, 5, 0, 3, 2, 4, 5, 6, 7 };
   findLargestDivibleNumber(n, v);
   return 0;
}

Output

If you run the above code, then you will get the following result.

765544320

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 09-Apr-2021 17:18:16
Advertisements