C++ Program To Find The Roots Of Quadratic Equation
Last Updated :
20 Mar, 2024
Given a quadratic equation in the form ax2 + bx + c, find roots of it.Â
Examples:
Input : Â a = 1, b = -2, c = 1
Output: Â Roots are real and same
       1
Input :Â a = 1, b = 7, c = 12
Output:Â Roots are real and different
       -3, -4
Input :Â a = 1, b = 1, c = 1
Output: Â Roots are complexÂ
       -0.5 + i1.73205
       -0.5 – i1.73205 Â
Below is the direct formula for finding the roots of the quadratic equation.
There are the following important cases:
1. If b*b < 4*a*c, then roots are complex (not real).
Example:Â
roots of x2 + x + 1, roots are:Â
-0.5 + i0.86603 and -0.5 – i0.86603
2. If b*b == 4*a*c, then roots are real and both roots are same.
Example:Â
roots of x2 – 2x + 1 are 1 and 1
3. If b*b > 4*a*c, then roots are real and different.
Example:
roots of x2 – 7x – 12 are 3 and 4
Roots of Quadratic Equation FlowchartÂ
Below is the C++ program to implement the above approach:
C++
// C++ program to find roots of
// a quadratic equation
#include <bits/stdc++.h>
using namespace std;
// Prints roots of quadratic equation
// ax*2 + bx + x
void findRoots(int a, int b, int c)
{
// If a is 0, then equation is
// not quadratic, but linear
if (a == 0) {
cout << "Invalid";
return;
}
int d = b * b - 4 * a * c;
double sqrt_val = sqrt(abs(d));
if (d > 0) {
cout << "Roots are real and different ";
cout << (double)(-b + sqrt_val) / (2 * a) << " "
<< (double)(-b - sqrt_val) / (2 * a);
}
else if (d == 0) {
cout << "Roots are real and same ";
cout << -(double)b / (2 * a);
}
// d < 0
else {
cout << "Roots are complex ";
cout << -(double)b / (2 * a) << " + i"
<< sqrt_val / (2 * a) << " "
<< -(double)b / (2 * a) << " - i"
<< sqrt_val / (2 * a);
}
}
// Driver code
int main()
{
int a = 1, b = -7, c = 12;
// Function call
findRoots(a, b, c);
return 0;
}
Output
Roots are real and different 4 3
The complexity of the above method
Time Complexity: O(log(D)), where D is the discriminant of the given quadratic equation.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...