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
Top comments (8)
Hi Klecianny,
I would like to offer two alternative implementations. Not better (probably worse), just different approaches. There is still a double pass through the array, just not as explicate as in your solution.
Using reduce & filter methods
Using recursion with a filter method
Hello @tracygjg, how are you? Thank you very much for this solutions for the current problem! Programming is fascinating because we can solve the same problem in different ways. I look forward to your interactions in future articles! 😁
No! *prepares cup of tea* >:3
Oh, good! Tea is a nice drink too 🥰
Very interesting this solution, use two loops is 🤯
Thank you my dear! Two loops is the power 😎
Nice algorithm for study
It's true Lala, thank you for your contribution! 🥰