Finding two golden numbers in JavaScript

We are required to write a JavaScript function that takes in two numbers representing a sum and product, and returns two numbers whose sum equals the first parameter and product equals the second parameter. If no such numbers exist, the function should return false.

Problem Understanding

Given sum s and product p, we need to find two numbers x and y such that:

  • x + y = s
  • x × y = p

Mathematical Approach

This is essentially solving a quadratic equation. If x + y = s and x × y = p, then y = s - x. Substituting into the product equation: x(s - x) = p, which gives us x² - sx + p = 0.

Example Implementation

const goldenNumbers = (sum, prod) => {
    for(let i = 0; i 

false
[ 5, 9 ]
[ 7, 14 ]

How It Works

The function iterates through possible values of the first number from 0 to half the sum. For each value i, it calculates the second number as sum - i and checks if their product equals the target product. If a match is found, it returns both numbers; otherwise, it returns false.

Optimized Version Using Quadratic Formula

const goldenNumbersOptimized = (sum, prod) => {
    // Using quadratic formula: x = (sum ± ?(sum² - 4×prod)) / 2
    const discriminant = sum * sum - 4 * prod;
    
    if (discriminant 

[ 5, 9 ]
[ 7, 14 ]
false

Comparison

Method Time Complexity Accuracy
Iterative Approach O(n) High for integers
Quadratic Formula O(1) High with floating-point precision

Conclusion

Both approaches solve the problem effectively. The iterative method is simpler to understand, while the quadratic formula approach is more mathematically elegant and efficient for large sums.

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

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements