Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python

PythonServer Side ProgrammingProgramming

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

Example

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

Input

4, 27

Output

10
raja
Updated on 25-Oct-2021 07:59:43

Advertisements