Divisible Sum Pairs

Divisible Sum Pairs

Divisible Sum Pairs:

You are given an array of n integers , \(a_0\) ,\(a_1\) ,….\(a_n-1\) and a positive integer, k Find and print the number of (i,j) pairs where i < j and \(a_i\) + \(a_j\) is evenly divisible by k.

Input Format

The first line contains 2 space-separated integers n and k respectively. The second line contains n space-separated integers describing the respective values of \(a_0\) ,\(a_1\) ,….\(a_n-1\)

Constraints:
  • 2<=n<=100
  • 2<=k<=100
  • 2<= \(a_i\) <=100
Output Format

Print the number of (i,j) pairs where i<j and \(a_i\) + \( a_j\) is evenly divisible by k .

Sample Input
6 3
1 3 2 6 1 2
Sample Output
5

Explanation

Here are the 5 valid pairs:

  • (0,2)–> \(a_0 + a_2\) = 1+2 =3
  • (0,5)–> \(a_0 + a_5\) = 1+2 =3
  • (1,3)–> \(a_1 + a_3 \) = 3+6 =9
  • (2,4)–> \(a_2+ a_4 \) = 2+1 =3
  • (4,5)–> \(a_4 + a_5 \) = 1+2 =3

Solution

#!/bin/python

import sys
def divisible_sum_pairs(n, k, a):
    return len([True for j in range(n - 1, 0, -1) for i in range(j) if not (a[i] + a[j]) % k])

n,k = raw_input().strip().split(' ')
n,k = [int(n),int(k)]
a = map(int,raw_input().strip().split(' '))

print(divisible_sum_pairs(n, k, a))
comments powered by Disqus