Examples [code] [code]
- User
Examples
input6 3 1 3 9 8 24 1output5 Assistant
6 3
1 3 9 8 24 1
5
Given:
Hypothesis: This appears to be asking for the number of pairs (i, j) where i < j and (a[i] + a[j]) is divisible by k.
Verification:
Step 1: Find remainders when each element is divided by k=3
Step 2: Group by remainder
Step 3: Find pairs whose sum is divisible by 3 For (a + b) % 3 == 0:
Total = 3 + 2 = 5 ✓
This matches the expected output!
Algorithm:
This problem asks for the number of pairs (i, j) where i < j and (a[i] + a[j]) is divisible by k.
For two numbers a and b:
This means we need pairs where:
Input: n=6, k=3, array=[1, 3, 9, 8, 24, 1]
Step 1: Compute remainders modulo 3
| Element | Remainder |
|---|---|
| 1 | 1 |
| 3 | 0 |
| 9 | 0 |
| 8 | 2 |
| 24 | 0 |
| 1 | 1 |
Step 2: Count by remainder
Step 3: Count valid pairs
Total = 3 + 2 = 5 ✓
def solve():
n, k = map(int, input().split())
arr = list(map(int, input().split()))
# Count elements by remainder
remainder_count = [0] * k
for x in arr:
remainder_count[x % k] += 1
# Count pairs with sum divisible by k
result = 0
# Pairs where both elements are divisible by k
result += remainder_count[0] * (remainder_count[0] - 1) // 2
# Pairs where remainders sum to k
for r in range(1, (k + 1) // 2):
result += remainder_count[r] * remainder_count[k - r]
# If k is even, pairs where both have remainder k/2
if k % 2 == 0:
result += remainder_count[k // 2] * (remainder_count[k // 2] - 1) // 2
print(result)
solve()
Answer: 5