← Back to challenges

Sum and Product

JavaScriptHardalgebramathnumbers

Instructions

Write a function that takes in two floating-point numbers s and p and returns two floating-point numbers [x, y], where x + y = s and x * y = p. Round x and y to three decimal places.

If there are multiple solutions, return the solution with the lesser x (or lesser y, if the x values are equal).

Imaginary/complex number solutions are not allowed. If no real-valued solutions exist, return null.

Examples

sumAndProduct(2, -15) ➞ [-3.0, 5.0]

sumAndProduct(144, 144) ➞ [1.007, 142.993]

sumAndProduct(-42.7, 144.5) ➞ [-38.994, -3.706]

sumAndProduct(10, 30) ➞ null

Notes

To solve this problem, consider setting up a system of two equations and solving for x and y.

javascript
Loading editor…
to run
Walks through the solution with reasoning and edge cases.