solve a quadratic equation using square roots code example
Example 1: Write a javascript program to find roots of quadratic equation.
let root1, root2;
let a = prompt("Enter the first number: ");
let b = prompt("Enter the second number: ");
let c = prompt("Enter the third number: ");
let discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
console.log(`The roots of quadratic equation are ${root1} and ${root2}`);
}
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
console.log(`The roots of quadratic equation are ${root1} and ${root2}`);
}
else {
let realPart = (-b / (2 * a)).toFixed(2);
let imagPart = (Math.sqrt(-discriminant) / (2 * a)).toFixed(2);
console.log(
`The roots of quadratic equation are ${realPart} + ${imagPart}i and ${realPart} - ${imagPart}i`
);
}
Example 2: public class QuadraticEquation { public static Roots findRoots
public class QuadraticEquation {
public static Roots findRoots(double a, double b, double c) {
Roots root = new Roots(0,0);
double root1, root2;
if(a==0 ||b==0||c==0) return root;
double determinant = (b * b) - (4 * a * c);
if (determinant > 0) {
root1 = (-b + Math.sqrt(determinant)) / (2 * a);
root2 = (-b - Math.sqrt(determinant)) / (2 * a);
}
else if (determinant == 0) {
root1 = -b / (2 * a);
root2 = root1;
} else {
root1= -b / (2 * a);
root2 = Math.sqrt(-determinant) / (2 * a);
}
root = new Roots(root1,root2);
return root;
}
public static void main(String[] args) {
Roots roots = QuadraticEquation.findRoots(2, 10, 8);
System.out.println("Roots: " + roots.x1 + ", " + roots.x2);
roots = QuadraticEquation.findRoots(1, -18, 81);
System.out.println("Roots: " + roots.x1 + ", " + roots.x2);
}
}
class Roots {
public final double x1, x2;
public Roots(double x1, double x2) {
this.x1 = x1;
this.x2 = x2;
}
}