Open In App

Java Program to Find the Roots of Quadratic Equation

Improve
Improve
Like Article
Like
Save
Share
Report

The roots of a function are the x-intercepts. By definition, the y-coordinate of points lying on the x-axis is zero. Therefore, to find the roots of a quadratic function, we set f (x) = 0, and solve the equation, ax2 + bx + c = 0.

Conditions for a quadratic equation – 

ax^2 + bx + c = 0 

where 
a, b, c are real numbers and cannot be zero ie, there value must be from {-∞ to -1} and {1 to ∞}

A mathematical formula for finding the roots of a quadratic equation – 

roots = (-b ± √(b2-4ac)) / (2a)

± represents there are two roots.

The roots of the quadratic equations are – 

first = (-b + √(b2-4ac)) / (2a)
second = (-b - √(b2-4ac)) / (2a)

The (b^2 – 4ac) which is the determinant, tells us about the nature of the roots –

  1. if (b^2 – 4ac) > 0, roots are real and different
  2. if (b^2 – 4ac) == 0, roots are real and equal
  3. if (b^2 – 4ac) < 0, roots are complex and different

Code to find roots of a quadratic equation:

Java
// Java program to find the roots of
// quadratic equation

public class Main {

    public static void main(String[] args)
    {

        // value of the constants a, b, c
        double a = 7.2, b = 5, c = 9;

        // declared the two roots
        double firstroot, secondroot;

        // determinant (b^2 - 4ac)
        double det = b * b - 4 * a * c;

        // check if determinant is greater than 0
        if (det > 0) {

            // two real and distinct roots
            firstroot = (-b + Math.sqrt(det)) / (2 * a);
            secondroot = (-b - Math.sqrt(det)) / (2 * a);

            System.out.format(
                "First Root = %.2f and Second Root = %.2f",
                firstroot, secondroot);
        }

        // check if determinant is equal to 0
        else if (det == 0) {

            // two real and equal roots
            // determinant is equal to 0
            // so -b + 0 == -b
            firstroot = secondroot = -b / (2 * a);

            System.out.format(
                "First Root = Second Root = %.2f;",
                firstroot);
        }

        // if determinant is less than zero
        else {

            // roots are complex number and distinct
            double real = -b / (2 * a);

            double imaginary = Math.sqrt(-det) / (2 * a);

            System.out.printf("First Root = %.2f+%.2fi",
                              real, imaginary);
            System.out.printf("\nSecond Root = %.2f-%.2fi",
                              real, imaginary);
        }
    }
}

Output
First Root = -0.35+1.06i
Second Root = -0.35-1.06i

Time Complexity: O(log(D)), where D is the discriminant of the given quadratic equation.
Auxiliary Space: O(1)



Last Updated : 20 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads