Write a program that calculates the real solutions of a third degree equation \(x^3 +ax^2+bx+c=0\).
The analytical method to follow:
- calculate $Q=\frac{a^2-3b}{9}$ and $R=\frac{2a^3-9ab+27c}{54}$
- If $R^2<Q^3$, we have 3 solutions
- $x_1=-2\sqrt{Q}\cos{(\frac{\theta}{3})}-a/3$
- $x_2=-2\sqrt{Q}\cos{(\frac{\theta+ 2 \pi}{3})}-a/3$
- $x_3=-2\sqrt{Q}\cos{(\frac{\theta - 2\pi}{3})}-a/3$
with $\theta = \arccos{(\frac{R}{\sqrt{Q^3}})}$
- Else, we have one real solution. To find it, calculate A and B such that:
- $A=-SIGN [|R|+\sqrt{R^2-Q^3}]^\frac{1}{3}$ where SIGN is the sign or R
- $B = \frac{Q}{A}$ if $A$ is different than 0, otherwise it is equal to 0
The real solution is thus: $x=(A+B)-\frac{a}{3}$
Display one or the 3 solutions (each number rounded to 2 numbers after the comma) followed by a new line.
$\pi$ is equal to 3.14.
Difficulty level

This exercise is mostly suitable for students
#include<stdio.h>
#include <math.h>
#define PI 3.14
int main()
{
int a,b,c;
double Q, R, x1,x2,x3, A,B, theta;
int sign = 1;
scanf("%d %d %d", &a,&b,&c);
Q= (double)(a*a - 3*b) / 9;
R = (double)(2*a*a*a - 9*a*b + 27*c)/54;
if(pow(R,2) < pow(Q,3))
{
theta = acos(R/sqrt(pow(Q,3)));
x1=-2*sqrt(Q)*cos(theta/3)-(double)a/3;
x2=-2*sqrt(Q)*cos((theta+2*PI)/3)-(double)a/3.0;
x3=-2*sqrt(Q)*cos((theta-2*PI)/3)-(double)a/3;
printf("%.2lf %.2lf %.2lf\n",x1,x2,x3);
}
else
{
if(R<0)
sign=-1;
A = - sign * pow((fabs(R) + sqrt(pow(R,2)-pow(Q,3))) ,1.0/3);
if(A==0)
B=0;
else
B=Q/A;
printf("%.2lf\n",(A+B)-a/3.0);
}
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
