
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Count Groups of Size 2 or 3 with Sum as Multiple of 3 in C++
In this tutorial, we will be discussing a program to find the number of possible groups of size 2 or 3 that have sum as multiple of 3.
In this tutorial, we will be discussing a program to find the number of possible groups of size 2 or 3 that have sum as multiple of 3.
Example
#include<bits/stdc++.h> using namespace std; //returning count of pairs of //2 or 3 int count_groups(int arr[], int n){ int c[3] = {0}, i; int res = 0; for (i=0; i<n; i++) c[arr[i]%3]++; res += ((c[0]*(c[0]-1))>>1); res += c[1] * c[2]; res += (c[0] * (c[0]-1) * (c[0]-2))/6; res += (c[1] * (c[1]-1) * (c[1]-2))/6; res += ((c[2]*(c[2]-1)*(c[2]-2))/6); res += c[0]*c[1]*c[2]; return res; } int main(){ int arr[] = {3, 6, 7, 2, 9}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Required number of groups are " << count_groups(arr,n) << endl; return 0; }
Output
Required number of groups are 8
Advertisements