HackerRank – Divisible Sum Pairs

Tue Feb 27 2018

Wanted to share my 2 solutions for this nice exercise, on is with 2 loops and the other with one loop and a recursion.

This is quite nice for a morning brain workout 😀

Exercise Description {#exercisedescription}

You are given an array of n integers, a0, a1a(n-1), and a positive integer, k. Find and print the number of (i,j) pairs where i

function getAmountOfPairs(n, k, nums) {  
    var counter = 0;

    for (var i = 0; i<nums.length-1 ; i++) {
        for (var j=i+1 ; j<nums.length ; j++) {
            if ((nums[i]+nums[j])%k == 0) {
                counter++;
            }   
        }
    }
    return counter;
}


function getAmountOfPairsRecursive(k, nums) {  
    var counter = 0;
    var elm = nums.shift();

    for (var i = 0; i<nums.length ; i++) {
        if ((elm+nums[i])%k == 0) {
            counter++;
        }   
    }
    if (nums.length==0) {
        return counter;
    } else {
        return counter + getAmountOfPairsRecursive(k, nums);
    }
}