javascript: reduces the complexity of nesting time for looping

Today I was doing a simple challenge in HackerRank with the following code, which is 100% acceptable and it works, but I was wondering if there was a way to further reduce the loops required by eliminating the duplicate calculations.

Let me visually show you what is happening. When I finish, my sample code will be very low!

The code takes the first number in an array of numbers and adds it to each subsequent number and checks if it is divisible by k = 3.

In a matrix of 6 numbers, that equals 15 loops, which would be O (n²), which means that my loops will grow exponentially to the input amount. 7 numbers would be 21 loops.

P. S., I could be thinking that 6 should be 21 loops and 7 should be 28, but keep in mind that I always take the current number and add it to the next, with the exception of the last number.

entry: [1, 3, 2, 6, 1, 2]

  • 1 + 3, 1 + 2, 1 + 6, 1 + 1, 1 + 2
  • 3 + 2, 3 + 6, 3 + 1, 3 + 2
  • 2 + 6, 2 + 1, 2 + 2
  • 6 + 1, 6 + 2
  • 1 + 2

If you look at the numbers that I've put in bold font, you will see that they are duplicate calculations. the italics the numbers are numbers divisible by k = 3. Now we are coming to my flesh of my question. How can I eliminate this duplicate math, which would reduce my loops from 15 to 8 in this particular example? The algorithm would still have a worse scenario than O (n²), if all the numbers were different, but this would be an optimization anyway.

divisible functionSumPairs (k, a) {
leave pairs = 0;
for (be i = 0; i <a.length - 1; i ++) {
for (be j = i + 1; j <a.length; j ++) {
yes ((ar[i] + ar[j]) / k% 1 === 0) pairs ++;
}
}
console.log (pairs);
}

divisibleSumPairs (3, [ 1, 3, 2, 6, 1, 2 ])