- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

- Related Questions & Answers
- Number of substrings divisible by 8 and not by 3 in C++
- Maximum number of groups of size 3 containing two type of items in C++
- Maximum number of 3-person teams formed from two groups in C++
- Check if a large number is divisible by 3 or not in java
- Check if a large number is divisible by 3 or not in C++
- Number of digits to be removed to make a number divisible by 3 in C++
- Find permutation of n which is divisible by 3 but not divisible by 6 in C++
- Greatest Sum Divisible by Three in C++
- Largest N digit number divisible by given three numbers in C++
- Possible cuts of a number such that maximum parts are divisible by 3 in C++
- Check if a large number is divisible by 2, 3 and 5 or not in C++
- Count all possible groups of size 2 or 3 that have sum as multiple of 3 in C++
- Number is divisible by 29 or not in C++
- Check if any permutation of a number is divisible by 3 and is Palindromic in Python
- How to create three-dimensional arrays of different sizes in R?