"You are given an array of n integers and an integer k. Find and print the number of (i,j) pairs where i<j and a[i] + a[j] is evenly divisible by k."
Sample input would be:
6 3
1 3 2 6 1 2
where 6 is n, 3 is k and the second line is the array of integers. The output for this input would be 5.
Here is my code, but i am not passing the test cases and am almost positive it has to do with how i am indexing it.
import sys
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
count=0;
for i in range(n):
curr = n-i
for j in range(curr):
if i < i + j:
if k % (a[i] + a[i+j]) ==0:
count = count + 1
print(count)
Also, followup question: Is this method i am approaching an efficient way of going about it?
i+jin your code as thejin the question, right? If yes, you are solving it not fori<i+jbut fori<=i+j.You also you need to move thekto the right hand side when checking for divisibilityfor j in range(curr):is good. I would do ratherfor j in range(i+1, n):Thisi < i + j:you can write as0 < j. This is wrongk % (a[i] + a[i+j]) == 0- you need(a[i] + a[i+j]) % k == 0. Besides I would usefor i in range(n-1):(without last element - you don't have to compare last element with last element)