Factorial in Java

后端 未结 7 1395
庸人自扰
庸人自扰 2020-12-11 08:08

I\'ve been using this factorial program for Java:

public static long factorial(int a) {

    if(a<1) {
        return 1;
    }
    long result=1;
    long         


        
7条回答
  •  情书的邮戳
    2020-12-11 08:55

    Overflow (and underflow) is silent according to the JLS, which is why your result was a "surprise".

    You have two choices:

    • if an exact answer is required, use BigInteger
    • if exactness is not required, use double (although even that will overflow past 170!)

提交回复
热议问题