Sum and Product

Published by Mubashir Hassan in

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 nil.

Examples

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

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

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

sum_and_product(10, 30) ➞ nil

Notes

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

Watch a quick demo on how Edabit works.