C/C++ Program to check whether it is possible to make a divisible by 3 number using all digits in an array

Given an array of integers, the task is to find whether it is possible to construct an integer using all the digits of these numbers such that it would be divisible by 3. If it is possible then print “Yes” and if not print “No”.

Examples:

Input : arr[] = {40, 50, 90}
Output : Yes
We can construct a number which is
divisible by 3, for example 945000. 
So the answer is Yes. 

Input : arr[] = {1, 4}
Output : No
The only possible numbers are 14 and 41,
but both of them are not divisible by 3, 
so the answer is No.
filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find if it is possible
// to make a number divisible by 3 using
// all digits of given array
#include <bits/stdc++.h>
using namespace std;
  
bool isPossibleToMakeDivisible(int arr[], int n)
{
    // Find remainder of sum when divided by 3
    int remainder = 0;
    for (int i = 0; i < n; i++)
        remainder = (remainder + arr[i]) % 3;
  
    // Return true if remainder is 0.
    return (remainder == 0);
}
  
// Driver code
int main()
{
    int arr[] = { 40, 50, 90 };
    int n = sizeof(arr) / sizeof(arr[0]);
    if (isPossibleToMakeDivisible(arr, n))
        printf("Yes\n");
    else
        printf("No\n");
  
    return 0;
}

chevron_right


Output:

Yes

Time Complexity: O(n)

Please refer complete article on Possible to make a divisible by 3 number using all digits in an array for more details!

My Personal Notes arrow_drop_up
Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.