- 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

Suppose we have a number n and another value k, consider we have an array A with first N natural numbers, we have to find the total number of pairs of elements A[i] and A[j] from A, such that, i < j and their sum is divisible by k.

So, if the input is like n = 10 k = 4, then the output will be 10 because there are 10 pairs whose sum is divisible by 4. [(1,3), (1,7), (2,6), (2,10), (3,5), (3,9), (4,8), (5,7), (6,10), (7,9)]

To solve this, we will follow these steps −

- m := floor of (n / k), r := n mod k
- b := a new map
- for i in range 0 to k - 1, do
- b[i] := m

- for i in range m*k+1 to n, do
- j := i mod k
- b[j] := b[j] + 1

- c := 0
- for i in range 0 to k, do
- i1 := i
- i2 :=(k - i) mod k
- if i1 is same as i2, then
- c := c + b[i] *(b[i]-1)

- otherwise,
- c := c + b[i1] *(b[i2])

- return floor of c/2

Let us see the following implementation to get better understanding −

def solve(n, k): m = n // k r = n % k b = {} for i in range(k) : b[i] = m for i in range(m*k+1, n+1) : j = i % k b[j] = b[j] + 1 c = 0 for i in range(k) : i1 = i i2 = (k - i) % k if i1 == i2 : c = c + b[i] * (b[i]-1) else : c = c + b[i1] * (b[i2]) return c//2 n = 10 k = 4 print(solve(n, k))

4, 27

10

- Related Questions & Answers
- Number of pairs from the first N natural numbers whose sum is divisible by K in C++
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Sum of first N natural numbers which are divisible by X or Y
- Maximize the number of sum pairs which are divisible by K in C++
- Count pairs in array whose sum is divisible by K in C++
- Sum of first N natural numbers which are divisible by 2 and 7 in C++
- Program to find max number of K-sum pairs in Python
- Check if product of first N natural numbers is divisible by their sum in Python
- Count pairs of numbers from 1 to N with Product divisible by their Sum in C++
- Java program to find the sum of n natural numbers
- PHP program to find the sum of first n natural numbers that are divisible by a number ‘x’ or a number ‘y’
- Count of pairs from 1 to a and 1 to b whose sum is divisible by N in C++
- Program to find sum of first n natural numbers in C++
- Sum of the natural numbers (up to N) whose modulo with K yield R in C++
- Find number of substrings of length k whose sum of ASCII value of characters is divisible by k in C++

Advertisements