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

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that counts the pairs whose sum is divisible by K.

Let's see the steps to solve the problem.

  • Initialise the N and K.

  • Generate the natural numbers till N and store them in an array.

    • Compute the sum of every pair.

    • If the pair sum is divisible by K, then increment the count.


Let's see the code.

 Live Demo

#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) {
   return count;
int main() {
   vector<int> arr;
   int N = 10, K = 5;
   for (int i = 1; i <= N; i++) {
   cout << get2PowersCount(arr, N, K) << endl;
   return 0;


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



If you have any queries in the tutorial, mention them in the comment section.

Published on 03-Jul-2021 08:26:28