Search

# Cocubes coding | All roots of quadratic equation

In this blog, we will learn how to find all the roots present in the equation.

First of all, you should have basic knowledge of the quadratic equation.

The general form of a quadratic equation is (ax^2 + bx + c = 0).The highest degree in a quadratic equation is 2. Hence, a quadratic equation will have two roots.

The formula to find the roots of a quadratic equation is given as follows

x = [-b +/- sqrt(-b^2 - 4ac)] / 2a

The discriminant of the quadratic equation is k = (b^2 - 4ac).

Depending upon the nature of the discriminant, the roots can be found in different ways.

1. If the discriminant is positive, then there are two distinct real roots.

2. If the discriminant is zero, then the two roots are equal.

3. If the discriminant is negative, then there are two distinct complex roots.

### Implementation Using Java:

```import java.util.*;

public class Main{
public static void main(String[] args)
{
double a, b, c, dis, r1, r2, rp, ip;
Scanner sc = new Scanner(System.in);
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
dis = b*b - 4*a*c; //discriminant

if(dis > 0)
{
r1 = (-b + Math.sqrt(dis))/(2*a);
r2 = (-b - Math.sqrt(dis))/(2*a);

System.out.println("root 1 =" + r1 + "and root 2 = "+r2);
}
else
{
rp = -b/(2*a);
ip = Math.sqrt(-dis)/(2*a);
System.out.println("root 1 = "+rp+ "+" +ip+"and root 2="+ rp + "+" + ip);
}
}
}```
```Output:
1 2 3
root 1 =-1+1.141421 and root 2 =-1+1.41421```

Happy Coding!

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

See All