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.

Example

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

Conclusion

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

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