0

While I was doing the code to pass the roots of quadratic equation using an array list, I encountered the wrong answer for the given test case 752 904 164. Its answer was -1,-1, but my answer was 0,0, so I tried searching for the solution and found I have to use the Math.floor() function, and after using that function, my test case runs successfully.

public ArrayList<Integer> quadraticRoots(int a, int b, int c) {
    // code here
    ArrayList alist = new ArrayList();
    double root1 ,root2 ;
    double d = (b*b)-(4*a*c);
    if (d<0)
    { 
        root1 = (-b+Math.sqrt(d))/2*a;
        alist.add(-1);
        return alist;
        
        
    }
    else
    {
        double srt= Math.sqrt(d);
        root1 = (-b+srt)/(2*a);
        root2 = (-b-srt)/(2*a);
        alist.add((int)Math.floor(Math.max(root1,root2)));  // 
        alist.add((int)Math.floor(Math.min(root1,root2)));
        return alist;
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    Why are you casting the results to `int`? I suggest you try without that *and* without the call to `Math.floor`, and you'll see what's going on... – Jon Skeet May 20 '22 at 13:56
  • You're losing precision by returning ArrayList, how about changing that to ArrayList? – Jonathan Sudiaman May 20 '22 at 13:58
  • Your `root1` will be evaluated wrong for a negative `d`, as it will be equivalent to `((-b + sqrt(d)) * a) / 2`. Don't forget parenthesis – Rogue May 20 '22 at 14:00
  • 1
    `ArrayList alist` : it is recommended not to use raw types! [JLS 4.8](https://docs.oracle.com/javase/specs/jls/se18/html/jls-4.html#jls-4.8-400): "*The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of generics into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.*" – user16320675 May 20 '22 at 14:00

0 Answers0