Factorial java return 0

后端 未结 4 1626
轻奢々
轻奢々 2021-01-24 06:51

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 {
       pub         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-24 07:25

    Java int is a primitive signed type stored in 32-bits, that means it has a valid range of -231 to 231-1 (see also Integer.MIN_VALUE and Integer.MAX_VALUE). In Java 8+ you might calculate the factorial using lambdas and taking the range of int values from 2 to n, mapping them to BigInteger and then reduction of the values with multiplication; Like

    public static BigInteger factorial(int n) {
        if (n < 0) {
            return BigInteger.ZERO;
        }
        return IntStream.rangeClosed(2, n).mapToObj(BigInteger::valueOf) //
                .reduce(BigInteger.ONE, (a, b) -> a.multiply(b));
    }
    

提交回复
热议问题