Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding two numbers that produce equal to the sum of rest in JavaScript
We have a sequence of numbers from 1 to any arbitrary number. We need to find pairs of numbers (m and n) from this sequence such that the sum of all remaining numbers equals the product of these two numbers.
Problem Statement
Given a number num, find all pairs [m, n] where:
sum(1 to num) - (m + n) = m * n
For example, if num = 10:
- Sum of 1 to 10 = 55
- For pair [6, 7]: 55 - (6 + 7) = 42 and 6 × 7 = 42 ?
Mathematical Approach
We can rearrange the equation algebraically:
sum - (m + n) = m * n sum - m - n = m * n sum - n = m * n + m sum - n = m * (n + 1) m = (sum - n) / (n + 1)
This gives us a formula to find m for any given n.
Example
const num = 10;
const pickNumbers = (num) => {
// Calculate sum of 1 to num using formula: n(n+1)/2
const sum = (num) * (num + 1) * 0.5;
const results = [];
for (let n = 1; n <= num; n++) {
let numerator = sum - n;
let denominator = n + 1;
// Check if m is a whole number
if (numerator % denominator === 0) {
let m = numerator / denominator;
// Ensure m is within range, different from n, and pair is unique
if (m < num && m !== n && m > 0 &&
results.every(group => group[0] + group[1] !== m + n)) {
results.push([m, n]);
}
}
}
return results;
};
console.log(pickNumbers(10));
Output
[ [ 6, 7 ] ]
How It Works
- Calculate total sum: Using formula n(n+1)/2 for sum of consecutive integers
- Iterate through possible values: For each n from 1 to num
- Find corresponding m: Using derived formula m = (sum - n) / (n + 1)
- Validate conditions: Ensure m is positive, within range, different from n, and creates unique pairs
- Store valid pairs: Add qualifying pairs to results array
Testing with Different Values
// Test with different numbers
console.log("num = 5:", pickNumbers(5));
console.log("num = 15:", pickNumbers(15));
console.log("num = 20:", pickNumbers(20));
num = 5: [] num = 15: [ [ 10, 9 ], [ 6, 7 ] ] num = 20: [ [ 15, 14 ], [ 10, 9 ], [ 6, 7 ] ]
Conclusion
This algorithm efficiently finds number pairs where the sum of remaining numbers equals their product. The mathematical approach reduces the problem to a simple division check, making it both elegant and performant.
Advertisements
