#include <iostream>
#include <complex>
#include <cmath>
using std::complex, std::operator<<, std::ostream;
class Roots {
friend ostream& operator<<(ostream&, const Roots&);
public:
complex<int> x1, x2, x3;
Roots();
Roots(complex<int>, complex<int>, complex<int>);
};
ostream& operator<<(ostream& OS, const Roots& R)
{
if (R.x1.imag() or R.x2.imag() or R.x3.imag()) {
char a, b, c;
a = R.x1.imag() < 0 ? '-' : '+';
b = R.x2.imag() < 0 ? '-' : '+';
c = R.x3.imag() < 0 ? '-' : '+';
OS
<< R.x1.real() << a << R.x1.imag() << "i, "
<< R.x2.real() << b << R.x2.imag() << "i, "
<< R.x3.real() << c << R.x3.imag() << "i"
<< std::endl;
}
else {
OS << R.x1.real() << " " << R.x2.real() << " " << R.x3.real() << std::endl;
}
return OS;
}
Roots::Roots() : x1(0), x2(0), x3(0) { }
Roots::Roots(complex<int> a, complex<int> b, complex<int> c) : x1(a), x2(b), x3(c) { }
// 一元三次方程式
class CubicEquation {
public:
int a, b, c, d;
Roots R;
CubicEquation(int, int, int, int);
private:
int A, B, C;
double D;
};
CubicEquation::CubicEquation(int a, int b, int c, int d) : a(a), b(b), c(c), d(d) {
A = b * b - 3 * a * c;
B = b * c - 9 * a * d;
C = c * c - 3 * b * d;
D = B * B - 4 * A * C;
if (A == B and !B) {
R = { -b / 3 * a, -c / b, -3 * d / c };
}
else if (D > 0) {
double y1, y2;
y1 = A * b + 3 * a * ((-B + sqrt(B * B - 4 * A * C)) / 2);
y2 = A * b + 3 * a * ((-B - sqrt(B * B - 4 * A * C)) / 2);
complex<int> x1{ static_cast<int> (round((-b - (pow(y1, (1. / 3)) + pow(y2, (1. / 3)))) / (3 * a))) };
complex<int> x2{ static_cast<int> (round((-b + .5 * (pow(y1, (1. / 3)) + pow(y2, (1. / 3)))) / (3 * a))), static_cast<int> (round(((sqrt(3) / 2) * (pow(y1, (1. / 3)) + pow(y2, (1. / 3)))) / (3 * a))) };
complex<int> x3{ static_cast<int> (round((-b + .5 * (pow(y1, (1. / 3)) + pow(y2, (1. / 3)))) / (3 * a))), static_cast<int> (round(-((sqrt(3) / 2) * (pow(y1, (1. / 3)) + pow(y2, (1. / 3)))) / (3 * a))) };
R = { x1, x2, x3 };
}
else if (not D) {
int K = B / A,
x1 = -b / a + K,
x2, x3 = x2 = -K / 2;
R = { x1, x2, x3 };
}
else {
auto T = (2 * A * b - 3 * a * B) / (2 * sqrt(A * A * A));
int x1 = static_cast<int> (round((-b - 2 * sqrt(A) * cos(acos(T) / 3)) / (3 * a))),
x2 = static_cast<int> (round((-b + sqrt(A) * (cos(acos(T) / 3) + sqrt(3) * sin(acos(T) / 3))) / (3 * a))),
x3 = static_cast<int> (round((-b + sqrt(A) * (cos(acos(T) / 3) - sqrt(3) * sin(acos(T) / 3))) / (3 * a)));
R = { x1, x2, x3 };
}
}
using std::cout, std::endl;
int main(void) {
// x^3 + 5x^2 - 2x - 24 = 0
CubicEquation E(1, 5, -2, -24);
cout << E.R;
return 0;
}