- 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

Given numbers N and K, we have to count the number of pairs whose sum is divisible by K. Let's see an example.

**Input**

N = 3 K = 2

**Output**

1

There is only one pair whose sum is divisible by K. And the pair is (1, 3).

- Initialise the N and K.
- Generate the natural numbers till N and store them in an array.
- Initialise the count to 0.
- Write two loops to get all pairs from the array.
- Compute the sum of every pair.
- If the pair sum is divisible by K, then increment the count.

- Return the count.

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

#include <bits/stdc++.h> using namespace std; int get2PowersCount(vector<int> arr, int N, int K) { 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 % K == 0) { count++; } } } return count; } int main() { vector<int> arr; int N = 10, K = 5; for (int i = 1; i <= N; i++) { arr.push_back(i); } cout << get2PowersCount(arr, N, K) << endl; return 0; }

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

9

- Related Questions & Answers
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Count pairs in array whose sum is divisible by K in C++
- Find the first natural number whose factorial is divisible by x in C++
- Check if product of first N natural numbers is divisible by their sum in Python
- Sum of first N natural numbers which are divisible by X or Y
- Sum of first N natural numbers which are divisible by 2 and 7 in C++
- Sum of sum of first n natural numbers in C++
- Maximize the number of sum pairs which are divisible by K in C++
- Find if given number is sum of first n natural numbers in C++
- Sum of first n natural numbers in C Program
- Count of pairs from 1 to a and 1 to b whose sum is divisible by N in C++
- Count pairs in array whose sum is divisible by 4 in C++
- Sum of the natural numbers (up to N) whose modulo with K yield R in C++
- Count pairs of numbers from 1 to N with Product divisible by their Sum in C++
- Smallest number that is divisible by first n numbers in JavaScript

Advertisements