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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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