Factorial java返回0

use*_*719 1 java factorial

我做了一个简单的函数来计算数字的阶乘,但从数字34返回0.它应该是51号.

   public class Métodos {
       public int factorial (int numero ){

          if ((numero <0)||(numero>50)){

           return 0;        
          } 

          else if ((numero == 0)||(numero == 1)){

           return 1;   
          }

          else{

           return numero * factorial(numero -1); 


          }

    }




    }
Run Code Online (Sandbox Code Playgroud)

谢谢 !

编辑:

好的,我怎么检查呢?

因为它说int不能转换为bigInteger.

 public static void main(String[] args) {
        // TODO code application logic here
         Métodos metod = new Métodos();
         System.out.print("El resultado es : " + metod.factorial(-12)+ "\n");
         System.out.print("El resultado es : " + metod.factorial(-1)+ "\n");
         System.out.print("El resultado es : " + metod.factorial(0)+ "\n");
         System.out.print("El resultado es : " + metod.factorial(1)+ "\n");
         System.out.print("El resultado es : " + metod.factorial(5)+ "\n");
         System.out.print("El resultado es : " + metod.factorial(51)+ "\n");
         System.out.print("El resultado es : " + metod.factorial(520)+ "\n");
    }
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

阶乘34大约是3*10 38 - 它不适合a int,可以容纳2*10 9的数字.价值34!甚至不适合long.

如果您需要计算如此大数的阶乘,请改用BigIntegerclass.该类的对象可以保存任意大小的整数值.请注意,使用中缀运算符不会执行操作,但使用方法:

public BigInteger factorial (int numero ){
    if (numero < 0) {
        return BigInteger.ZERO;
    } else if (numero==0){
        return BigInteger.ONE;
    } else {
        return BigInteger.valueOf(numero).multiply(factorial(numero-1));
    }
}
Run Code Online (Sandbox Code Playgroud)