Divisible sum pairs

Klecianny Melo - May 2 - - Dev Community

Prepare your favorite cup of coffee, because we are about to enter the fantastic world of Divisible sum pairs.

The problem

Image description

Image description

The solution

Image description

To start our solution, let's define the divisibleSumPairs function that will receive the following parameters:

  • n: length of array arr;
  • k: integer divisor;
  • ar: input array.
function divisibleSumPairs(n, k, ar) {}
Enter fullscreen mode Exit fullscreen mode

Next we will initialize the counter variable with the value 0:

let counter = 0;
Enter fullscreen mode Exit fullscreen mode

Now let's go through the ar array from the first element to the penultimate element:

for (let i = 0; i < n - 1; i++) {}
Enter fullscreen mode Exit fullscreen mode

Inside the first loop, we will start a second loop, to cycle through the elements of the ar array from the i + 1 element to the last element:

for (let j = i + 1; j < n; j++) {}
Enter fullscreen mode Exit fullscreen mode

After traversing the array ar with the two loops (integrating through the element i and the element j (i + 1)), we will check if the sum of the elements in the indices i and j of the array arr is divisible by k without remainder:

if ((ar[i] + ar[j]) % k === 0) {}
Enter fullscreen mode Exit fullscreen mode

If this condition is met, we will increase the value of the counter variable:

counter++;
Enter fullscreen mode Exit fullscreen mode

Thus, we will have the number of pairs that satisfy this condition counted in counter.

Finally, let's return the value of counter:

return counter;
Enter fullscreen mode Exit fullscreen mode

Final resolution

Image description

After following the step by step we have our final resolution:

function divisibleSumPairs(n, k, ar) {
    let counter = 0;

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

    return counter;
}
Enter fullscreen mode Exit fullscreen mode

Share the code, spread knowledge and build the future! 😉

Images generated by DALL·E 3

. . . . . . . . . . . . . . . . . . . . . . . .