Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save daubattu/dde5c99dc947fb99e798798b24c50de2 to your computer and use it in GitHub Desktop.
Save daubattu/dde5c99dc947fb99e798798b24c50de2 to your computer and use it in GitHub Desktop.
[Hackerrank] Solution of Divisible Sum Pairs in JavaScript
function divisibleSumPairs(n, k, ar) {
let result = 0;
for(let i = 0; i < n - 1; i++) {
result += ar.slice(i + 1, n).filter((item, index) => {
if ((item + ar[i]) % k === 0) {
return item;
}
}).length;
}
return result;
}
@Mousamia
Copy link

Mousamia commented Feb 3, 2023

for(let i = 0; i < n; i++) {
for(let j = i + 1; j < n; j++ ) {
let sum = ar[i] + ar[j]
if(sum % k === 0) {
counter++
}
}
this does not work for single element ... the following code will work

function divisibleSumPairs(n, k, ar) {
// Write your code here
var sum = 0;
var pair = 0;

// for single element array where the element is divisible by k
if(n==1 && (ar[0]%k == 0)){
   pair = 1;
}
else if (n > 1){
    for(i = 0; i<n; i++){
        // for adding the values
        for(j = i+1; j<n; j++){
            sum = ar[i] + ar[j];
            if(sum % k == 0){
                pair++;
                // console.log("I am pair", pair);
            }
        }
    }
    
}
    
else {
    pair = 0;
}

return pair;

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment