Finding a pair that is divisible by some number in JavaScript

We need to write a JavaScript function that finds all pairs of numbers from an array whose sum is divisible by a given number. The function takes an array of numbers and a divisor as parameters.

Problem Statement

Given an array of numbers and a divisor, find all pairs where:

(arr[i] + arr[j]) % divisor === 0, and i < j

For example, with array [1, 2, 3, 4, 5, 6] and divisor 4, we need pairs whose sum is divisible by 4.

Input and Expected Output

Input:
const arr = [1, 2, 3, 4, 5, 6];
const num = 4;

Expected Output:
[
   [1, 3],  // 1 + 3 = 4, divisible by 4
   [2, 6],  // 2 + 6 = 8, divisible by 4  
   [3, 5]   // 3 + 5 = 8, divisible by 4
]

Solution Using Nested Loops

const arr = [1, 2, 3, 4, 5, 6];
const num = 4;

const divisibleSumPairs = (arr = [], num) => {
    const res = [];
    const { length } = arr;
    
    for(let i = 0; i < length; i++){
        for(let j = i + 1; j < length; j++){
            const sum = arr[i] + arr[j];
            if(sum % num === 0){
                res.push([arr[i], arr[j]]);
            }
        }
    }
    return res;
};

console.log(divisibleSumPairs(arr, num));
[ [ 1, 3 ], [ 2, 6 ], [ 3, 5 ] ]

How It Works

The algorithm uses a nested loop approach:

  1. Outer loop (i): Iterates through each element as the first element of potential pairs
  2. Inner loop (j): Starts from i + 1 to avoid duplicate pairs and ensure i < j
  3. Sum check: For each pair, calculate arr[i] + arr[j] and check if divisible by num
  4. Store result: If divisible, add the pair [arr[i], arr[j]] to results

Alternative Example

const numbers = [2, 4, 6, 8, 10];
const divisor = 3;

const result = divisibleSumPairs(numbers, divisor);
console.log("Pairs divisible by", divisor + ":");
console.log(result);

// Check the sums
result.forEach(pair => {
    const sum = pair[0] + pair[1];
    console.log(`${pair[0]} + ${pair[1]} = ${sum} (${sum} % ${divisor} = ${sum % divisor})`);
});
Pairs divisible by 3:
[ [ 2, 4 ], [ 4, 8 ], [ 6, 10 ] ]
2 + 4 = 6 (6 % 3 = 0)
4 + 8 = 12 (12 % 3 = 0)
6 + 10 = 16 (16 % 3 = 1)

Time and Space Complexity

  • Time Complexity: O(n²) due to nested loops checking all possible pairs
  • Space Complexity: O(k) where k is the number of valid pairs found

Conclusion

This solution efficiently finds all pairs whose sum is divisible by a given number using nested loops. The algorithm ensures no duplicate pairs by maintaining the condition i < j.

Updated on: 2026-03-15T23:19:00+05:30

370 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements