import java.util.*;
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.text.*;
import java.util.Locale;
//import Numeric;

class NA13D
{ 
public static double[][] cubic_roots(double d[])
{
// roots of a degree 3 polynomial
// P(x)=a[3]*x^3+a[2]*x^2+a[1]*x+a[0]=0;
// assuming all a is all real;
// if more than 4 values are entered the remaining ones will be ignored 
double x[][]=new double[2][3];
double a,b,c;
a=d[2]/d[3];
b=d[1]/d[3];
c=d[0]/d[3];
double Q,R,theta;
Q=(a*a-3.0*b)/9.0;
double x1,x2,x3,x4;
x1=2.0*a*a*a;
x2=-9*a*b;
x3=27*c;
x4=x1+x2+x3;
R=x4/54.0;
//System.out.println("Q="+Q+"R="+R+"x1="+x1+"x2="+x2+"x3="+x3+"x4="+x4);
double Q3=Q*Q*Q;
double R2=R*R;
double qq;
//System.out.println("Q3="+Q3+"R2="+R2+(R2<Q3));
double A,B;
if(R2<Q3)
{
qq=-2.0*Math.sqrt(Q);	
theta=Math.acos(R/Math.sqrt(Q3));
x[0][0]=qq*Math.cos(theta/3.0)-a/3.0;
x[0][1]=qq*Math.cos((theta-2.0*Math.PI)/3.0)-a/3.0;
x[0][2]=qq*Math.cos((theta+2.0*Math.PI)/3.0)-a/3.0;
}
else
{
A=-Math.pow((R+Math.sqrt(R2-Q3)),(1.0/3.0));
if(A==0) B=0;
else     B=Q/A;
x[0][0]=(A+B)-a/3.0;
x[0][1]=-0.5*(A+B)-a/3;
x[1][1]=Math.sqrt(3.0)/2.0*(A-B);
x[0][2]=-0.5*(A+B)-a/3;
x[1][2]=-Math.sqrt(3.0)/2.0*(A-B);
}
return x;
}


public static complex[] cubic_rootsC(double c[])
{
// roots of a degree 3 polynomial
//return 3 complex roots
double a[][]=new double[2][3];
a=cubic_roots(c);
complex e[]=new complex[3];
for(int i=0;i<3;i++)
  e[i]=new complex(a[0][i],a[1][i]);
return e;
}
     public static double[] enterdata(String s)
     {
     String s1=JOptionPane.showInputDialog(s);        
     StringTokenizer token=new StringTokenizer(s1);
     int n=token.countTokens()-1;
     int m=n+1;
     double a[]=new double[m];
     int j=0;           
     while(token.hasMoreTokens())
     {
     Double ax=new Double(token.nextToken());
     a[j++]=ax.doubleValue();
     }
     return a; 
     }	
     
  public static void main(String args[]) throws IOException
  {
  String s="enter coefficients of the third degree polynomial a[0]..a[3] y=a[0]+a[1]*x+,a[2]*x^2+a[3}*x^3: ";
  double [] x0=enterdata(s);
  complex z[]=cubic_rootsC(x0);
  String s1="";
  for(int i=0;i<3;i++)
    {s1+=complex.toString(z[i])+"\n";}
  JOptionPane.showMessageDialog(null,s1,
  "roots of the third degree polynomial : ",JOptionPane.PLAIN_MESSAGE);
  }
}
