- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 of pairs from 1 to a and 1 to b whose sum is divisible by N in C++
We are given an integer array and the task is to count the total number of pairs (x, y) that can be formed using the given array values such that the integer value of x is less than y.
Input − int a = 2, b = 3, n = 2
Output − Count of pairs from 1 to a and 1 to b whose sum is divisible by N are − 3
Explanation −
Firstly, We will start from 1 to a which includes 1, 2 Now, we will start from 1 to b which includes 1, 2, 3 So the pairs that can be formed are (1,1), (1,2), (1, 3), (2, 1), (2, 2), (2, 3) and their respective sum are 2, 3, 4, 3, 4, 5. The numbers 2, 4, 4 are divisible by the given N i.e. 2. So the count is 3.
Input − int a = 4, b = 3, n = 2
Output − Count of pairs from 1 to a and 1 to b whose sum is divisible by N are − 3
Explanation −
Firstly, We will start from 1 to a which includes 1, 2, 3, 4 Now, we will start from 1 to b which includes 1, 2, 3 So the pairs that can be formed are (1,1), (1,2), (1, 3), (2, 1), (2, 2), (2, 3), (3,1), (3, 2), (3, 3), (4, 1), (4, 2), (4, 3) and their respective sum are 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7. The numbers 3, 3, 6, 6 are divisible by the given N i.e. 3. So the count is 4
Approach used in the below program is as follows
Input integer variables a, b and n for 1 to a, 1 to b and divisibility comparison with n
Pass all the data to the function for further processing
Create a temporary variable count to store the pairs
Start loop FOR from i to 0 till a
Inside the loop, start another loop FOR from j to 0 till b
Inside the loop, set sum with i + j
Inside the loop, check IF sum % n == 0 then increment the count by 1
Return the count
Print the result
Example
#include <iostream> using namespace std; int Pair_a_b(int a, int b, int n){ int count = 0; for (int i = 1; i <= a; i++){ for (int j = 1; j <= b; j++){ int temp = i + j; if (temp%n==0){ count++; } } } return count; } int main(){ int a = 2, b = 20, n = 4; cout<<"Count of pairs from 1 to a and 1 to b whose sum is divisible by N are: "<<Pair_a_b(a, b, n); return 0; }
Output
If we run the above code it will generate the following output −
Count of pairs from 1 to a and 1 to b whose sum is divisible by N are: 10