← Back to challenges

Sum and Product

PythonHardalgebramathnumbers

Instructions

Write a function that takes in two floating-point numbers s and p and returns a tuple of 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 None.

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) ➞ None

Notes

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

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