Number of pairs from the first N natural numbers whose sum is divisible by K in C++



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).

Algorithm

  • 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.

Implementation

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; }

Output

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

9
Updated on: 2021-10-26T18:56:50+05:30

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements