AlgoMaster Logo

Roots of a Quadratic Equation

Last Updated: June 7, 2026

easy
3 min read

Understanding the Problem

The quadratic formula gives the roots of a*x^2 + b*x + c = 0 as x = (-b ± sqrt(b^2 - 4ac)) / (2a). The behavior of those roots hinges on the quantity under the square root, b^2 - 4ac, called the discriminant.

It matters because you cannot take the real square root of a negative number. When it is positive, the square root is real, and the plus and minus give two different real roots. When it is zero, the square root contributes nothing, so both signs collapse to a single repeated root. When it is negative, the square root is imaginary, and the roots become a complex conjugate pair. So branch on the sign of the discriminant and handle each case with its own formula.

Key Constraints:

  • a is not zero → Division by 2a is always safe, and the equation really is quadratic rather than linear.
  • The discriminant decides the case → Compute d = b^2 - 4ac first, then branch on whether it is positive, zero, or negative.
  • A negative discriminant means complex roots → You cannot take a real square root of a negative number, so handle this case by splitting into a real part and an imaginary magnitude.

Approach 1: Branch on the Discriminant

Intuition

Compute the discriminant once, then let its sign route you to the right formula.

If d > 0, take its real square root and plug into the quadratic formula twice, once with the plus and once with the minus, for two distinct real roots. Report the larger first.

If d == 0, the square root term vanishes, so both signs give the same root -b / (2a), one value to report.

If d < 0, rewrite the formula in terms of the magnitude sqrt(-d). The roots share a real part -b / (2a) and differ only in the sign of the imaginary part sqrt(-d) / (2a), giving the conjugate pair p + qi and p - qi.

Algorithm

  1. Compute the discriminant d = b*b - 4*a*c.
  2. If d > 0, compute (-b + sqrt(d)) / (2a) and (-b - sqrt(d)) / (2a), then return them with the larger first.
  3. If d == 0, compute -b / (2a) and return the single root.
  4. If d < 0, compute the real part -b / (2a) and the imaginary magnitude sqrt(-d) / (2a), then return the conjugate pair.

Example Walkthrough

Input:

1
a
2
b
5
c

Start with the discriminant: d = 2*2 - 4*1*5 = 4 - 20 = -16. Since d is negative, the roots are complex. The real part is -b / (2a) = -2 / 2 = -1. The imaginary magnitude is sqrt(16) / 2 = 4 / 2 = 2. The two roots are mirror images across the real axis, so the answer is -1.00 + 2.00i and -1.00 - 2.00i.

0
-
1
1
2
.
3
0
4
0
5
6
+
7
8
2
9
.
10
0
11
0
12
i
13
,
14
15
-
16
1
17
.
18
0
19
0
20
21
-
22
23
2
24
.
25
0
26
0
27
i
output

Code