Number of Groups of Sizes Two Or Three Divisible By 3 in C++

C++Server Side ProgrammingProgramming

Given an array of numbers, we need to find the number of groups of size 2 and 3 that are divisible by 3. We can get the sums of two and three combination numbers and check whether they are divisible by 3 or not.

Let's see an example.

Input

arr = [1, 2, 3, 4]

Output

4

There are 4 combinations that are divisible by 3. The combinations are...

[1, 2]
[2, 4]
[1, 2, 3]
[2, 3, 4]

Algorithm

  • Initialise the array.

  • Write two loops to get all combinations of size two.

    • Compute the sum of each group.

    • If the sum is divisible by 3, then increment the count.

  • Write three loops to get all combinations of size three.

    • Compute the sum of each group.

    • If the sum is divisible by 3, then increment the count.

  • Return the count.

Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
int getNumberOfGroupsDivisibleBy3(int arr[], int n) {
   int count = 0;
   for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
         int sum = arr[i] + arr[j];
         if (sum % 3 == 0) {
            count += 1;
         }
      }
   }
   for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
         for (int k = j + 1; k < n; k++) {
            int sum = arr[i] + arr[j] + arr[k];
               if (sum % 3 == 0) {
                  count += 1;
               }
         }
      }
   }
   return count;
}
int main() {
   int arr[] = { 2, 3, 4, 5, 6, 1, 2, 4, 7, 8 };
   int n = 10;
   cout << getNumberOfGroupsDivisibleBy3(arr, n) << endl;
   return 0;
}

Output

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

57
raja
Updated on 26-Oct-2021 12:25:13

Advertisements