HR - Divisible Sum Pairs

Goody·2021년 2월 4일
0

알고리즘

목록 보기
29/122

문제

Given an array of integers and a positive integer k , determine the number of (i,j)pairs where i<j and ar[i] + ar[j] is divisible by k .

Example

ar = [1,2,3,4,5,6]
k = 5
Three pairs meet the criteria: [1,4],[2,3], and [4,6] .

예시

INPUT

6 3
1 3 2 6 1 2

**OUTPUT

5

Explanation
Here are the 5 valid pairs when k = 3 :

풀이

  • 배열 내 원소끼리의 합이 k 로 나누어 떨어지는지 검사하는 문제이다.
  • ij 보다 무조건 작고, 두 수는 인접하지 않아도 된다.

코드

function divisibleSumPairs(n, k, ar) {

    let count = 0;
    let idx = 0;

    while(idx < n) {

        for(let i = (idx + 1); i < n; i++) {
            if((ar[idx] + ar[i]) % k === 0) count++;
        }
        idx++;
    }

    return count;
}

0개의 댓글