|
| 1 | +package com.thealgorithms.maths; |
| 2 | + |
| 3 | +/** |
| 4 | + * This class represents a complex number which has real and imaginary part |
| 5 | + */ |
| 6 | +class ComplexNumber { |
| 7 | + Double real; |
| 8 | + Double imaginary; |
| 9 | + |
| 10 | + ComplexNumber(double real, double imaginary) { |
| 11 | + this.real = real; |
| 12 | + this.imaginary = imaginary; |
| 13 | + } |
| 14 | + |
| 15 | + ComplexNumber(double real) { |
| 16 | + this.real = real; |
| 17 | + this.imaginary = null; |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * Quadratic Equation Formula is used to find |
| 23 | + * the roots of a quadratic equation of the form ax^2 + bx + c = 0 |
| 24 | + * |
| 25 | + * @see <a href="https://en.wikipedia.org/wiki/Quadratic_equation">Quadratic Equation</a> |
| 26 | + */ |
| 27 | +public class QuadraticEquationSolver { |
| 28 | + /** |
| 29 | + * Function takes in the coefficients of the quadratic equation |
| 30 | + * |
| 31 | + * @param a is the coefficient of x^2 |
| 32 | + * @param b is the coefficient of x |
| 33 | + * @param c is the constant |
| 34 | + * @return roots of the equation which are ComplexNumber type |
| 35 | + */ |
| 36 | + public ComplexNumber[] solveEquation(double a, double b, double c) { |
| 37 | + double discriminant = b * b - 4 * a * c; |
| 38 | + |
| 39 | + // if discriminant is positive, roots will be different |
| 40 | + if (discriminant > 0) { |
| 41 | + return new ComplexNumber[] {new ComplexNumber((-b + Math.sqrt(discriminant)) / (2 * a)), new ComplexNumber((-b - Math.sqrt(discriminant)) / (2 * a))}; |
| 42 | + } |
| 43 | + |
| 44 | + // if discriminant is zero, roots will be same |
| 45 | + if (discriminant == 0) { |
| 46 | + return new ComplexNumber[] {new ComplexNumber((-b) / (2 * a))}; |
| 47 | + } |
| 48 | + |
| 49 | + // if discriminant is negative, roots will have imaginary parts |
| 50 | + if (discriminant < 0) { |
| 51 | + double realPart = -b / (2 * a); |
| 52 | + double imaginaryPart = Math.sqrt(-discriminant) / (2 * a); |
| 53 | + |
| 54 | + return new ComplexNumber[] {new ComplexNumber(realPart, imaginaryPart), new ComplexNumber(realPart, -imaginaryPart)}; |
| 55 | + } |
| 56 | + |
| 57 | + // return no roots |
| 58 | + return new ComplexNumber[] {}; |
| 59 | + } |
| 60 | +} |
0 commit comments