I made a simple function to calculate the factorial of a number but from number 34 returns 0 . It should be from number 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);
}
}
}
Thanks !
Edit:
Ok,how can i check it ?
because it says int cannot be converted to 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");
}
The factorial of 34 is about 3*1038 - it does not fit into an int, which could hold numbers up to 2*109. The value of 34! would not fit even in a long.
If you need to calculate factorials of such large numbers, use BigInteger class instead. Objects of that class can hold integer values of arbitrary size. Note that the operations would not be done with the infix operators, but with methods:
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With