Find all the roots of a quadratic equation in C, C++, Java and Python | faceprep

Find all the roots of a quadratic equation in C, C++, Java and Python | faceprep

The program to find all the roots of a quadratic equation is discussed here.


Finding all the roots of a quadratic equation in C, C++, Java and Python

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.


Solving a quadratic equation

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.


Finding all the roots of a quadratic equation in C, C++, Java and Python

Case 1: If the discriminant is positive,


r1 = (-b +?k)/ 2a and r2 =(b +?k)/ 2a are the two roots.


Case 2: If the discriminant is zero,



r1 = r2 = (-b / 2a)are the two roots.


Case 3: If the discriminant is negative,


r1 = (-b +i ?k)/ 2a and r2 =(b + i?k)/ 2a are the two roots.


For example, consider the following equationnn2x^2 8x + 3 = 0.nna = 2, b = -8, c = 3nnDiscriminant value, k =b^2 - 4acn= 8^2 - 4*(-8)*3n = 40                                    nnThe discriminant value is positive. Hence, the roots are real and distinct.nnr1 = (-b +?k)/ 2an = (8 +?40) /2*2n = 2.3875nnr2 =(b +?k)/ 2an =(-8 +?40) /2*2n = -0.3875nnr1 = 2.3875andr2 = -0.3875 are the two roots.n


Algorithm to find all the roots of a quadratic equation

1. Input the value of a, b, c.

2. Calculate k = b*b – 4*a*c

3. If (d < 0)

Display “Roots are Imaginary, calculater1 = (-b +i ?k)/ 2a and r2 =(b + i?k)/ 2a.

else if (d = 0)

Display “Roots are Equal” and calculate r1 = r2 = (-b / 2*a)

else

Display “Roots are real and calculate r1 = -b + ?d / 2*a andr2 = -b – ?d / 2*a

4. Print r1 and r2.

5. End the algorithm.



Finding all the roots of a quadratic equation in C, C++, Java and Python

Program to find all the roots of a quadratic equation


@@coding::1@@


Time complexity: O(1)


Recommended Programs







Finding all the roots of a quadratic equation in C, C++, Java and Python

c