Prepare your favorite cup of coffee, because we are about to enter the fantastic world of Divisible sum pairs.
The problem
The solution
To start our solution, let's define the divisibleSumPairs
function that will receive the following parameters:
-
n
: length of arrayarr
; -
k
: integer divisor; -
ar
: input array.
function divisibleSumPairs(n, k, ar) {}
Next we will initialize the counter
variable with the value 0:
let counter = 0;
Now let's go through the ar
array from the first element to the penultimate element:
for (let i = 0; i < n - 1; i++) {}
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++) {}
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) {}
If this condition is met, we will increase the value of the counter
variable:
counter++;
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;
Final resolution
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;
}
Share the code, spread knowledge and build the future! 😉
Images generated by DALL·E 3