- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures

- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces

# 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

- Related Articles
- 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++
- 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
- Find the first natural number whose factorial is divisible by x in C++
- Sum of first N natural numbers which are divisible by 2 and 7 in C++
- Maximize the number of sum pairs which are divisible by K in C++
- PHP program to find the sum of first n natural numbers that are divisible by a number ‘x’ or a number ‘y’
- Find if given number is sum of first n natural numbers in C++
- Count of pairs from 1 to a and 1 to b whose sum is divisible by N in C++
- Smallest number that is divisible by first n numbers in JavaScript
- Count pairs of numbers from 1 to N with Product divisible by their Sum in C++
- Sum of sum of first n natural numbers in C++
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Check if an array can be divided into pairs whose sum is divisible by k in Python

Advertisements