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
Take two numbers m and n & return two numbers whose sum is n and product m in JavaScript
We need to write a JavaScript function that takes two numbers m (product) and n (sum) and returns two numbers whose sum equals n and product equals m. If no such numbers exist, the function should return false.
This is essentially solving a quadratic equation where we need to find two numbers x and y such that x + y = n and x × y = m.
Mathematical Approach
We can solve this using the quadratic formula. If x + y = n and x × y = m, then x and y are roots of the equation t² - nt + m = 0.
Example
const findNumbers = (product, sum) => {
// Using quadratic formula to find roots of t² - sum*t + product = 0
const discriminant = sum * sum - 4 * product;
// If discriminant is negative, no real solutions exist
if (discriminant < 0) {
return false;
}
const sqrtDiscriminant = Math.sqrt(discriminant);
const x = (sum + sqrtDiscriminant) / 2;
const y = (sum - sqrtDiscriminant) / 2;
// Check if solutions are valid (avoiding floating point errors)
if (Math.abs(x + y - sum) < 1e-10 && Math.abs(x * y - product) < 1e-10) {
return [x, y];
}
return false;
};
console.log(findNumbers(144, 24)); // Product: 144, Sum: 24
console.log(findNumbers(45, 14)); // Product: 45, Sum: 14
console.log(findNumbers(98, 21)); // Product: 98, Sum: 21
console.log(findNumbers(10, 3)); // Product: 10, Sum: 3 (impossible)
[ 12, 12 ] [ 5, 9 ] [ 7, 14 ] false
Alternative Brute Force Approach
For simpler cases or when dealing with integers, we can use a brute force method:
const findNumbersBruteForce = (product, sum) => {
for (let i = 0; i <= sum / 2; i++) {
const j = sum - i;
if (i * j === product) {
return [i, j];
}
}
return false;
};
console.log(findNumbersBruteForce(144, 24));
console.log(findNumbersBruteForce(45, 14));
console.log(findNumbersBruteForce(98, 21));
console.log(findNumbersBruteForce(10, 3));
[ 12, 12 ] [ 5, 9 ] [ 7, 14 ] false
Comparison
| Method | Time Complexity | Handles Decimals | Accuracy |
|---|---|---|---|
| Quadratic Formula | O(1) | Yes | High (with floating point check) |
| Brute Force | O(n) | Limited | Perfect for integers |
Key Points
- The quadratic formula approach is more efficient with O(1) time complexity
- Check the discriminant to determine if real solutions exist
- Use floating point comparison for accuracy when dealing with decimal results
- The brute force method works well for integer solutions
Conclusion
Both approaches solve the problem effectively. Use the quadratic formula for mathematical precision and efficiency, or the brute force method for simpler integer-based solutions.
