Write a Kotlin Program to Find all Roots of a Quadratic Equation

A quadratic equation is a polynomial equation of the second degree.

It can be expressed in the form of ax^2 + bx + c = 0, where a, b, and c are constants and x is a variable.

In this Kotlin tutorial, we will write a Kotlin program to find all the roots of a quadratic equation.

To find the roots of a quadratic equation, we can use the quadratic formula.

The quadratic formula is given by:

x = (-b ± √(b^2 – 4ac)) / 2a

Using this formula, we can find the roots of the quadratic equation.

There are three possible scenarios depending on the discriminant b^2 – 4ac of the equation:

  • If the discriminant is positive, the equation has two distinct real roots.
  • If the discriminant is zero, the equation has one real root.
  • If the discriminant is negative, the equation has two complex roots.

Let’s implement the above logic in Kotlin.

import kotlin.math.sqrt

fun main() {
    val a = 2.0
    val b = 5.0
    val c = 3.0

    val discriminant = b * b - 4.0 * a * c

    if (discriminant > 0) {
        val root1 = (-b + sqrt(discriminant)) / (2.0 * a)
        val root2 = (-b - sqrt(discriminant)) / (2.0 * a)
        println("The equation has two distinct real roots: $root1 and $root2")
    } else if (discriminant == 0.0) {
        val root = -b / (2.0 * a)
        println("The equation has one real root: $root")
    } else {
        val realPart = -b / (2.0 * a)
        val imaginaryPart = sqrt(-discriminant) / (2.0 * a)
        println("The equation has two complex roots: $realPart + $imaginaryPart i and $realPart - $imaginaryPart i")
    }
}

In the above code, we have used the sqrt function from the kotlin.math package to calculate the square root of the discriminant.

We have defined the values of a, b, and c as 2.0, 5.0, and 3.0 respectively. These values can be changed according to the equation we want to solve.

After calculating the discriminant, we have used the if-else statements to check the value of the discriminant and find the roots of the equation accordingly.

If the discriminant is greater than zero, we have calculated two distinct real roots using the quadratic formula and printed the result.

If the discriminant is zero, we have calculated one real root using the quadratic formula and printed the result.

If the discriminant is negative, we have calculated two complex roots using the quadratic formula and printed the result.

In conclusion, we have successfully implemented a Kotlin program to find all the roots of a quadratic equation using the quadratic formula.