Как обойти ограничение n <= 31, чтобы правильно вычислялось значение факториала? (т.е, чтобы вычислялось при n > 31)

public static int fact(int number, int result) {
        switch (number) {
            case 1: return result;
            default: return fact(number - 1, number * result);
        }   
    }
    public static void main(String[] args) {
        System.out.print("Введите n факториала: ");
        Scanner read = new Scanner(System.in);
        int n = read.nextInt();
        System.out.print(n + "! = " + fact(n, 1));
    }

Ответы (1 шт):

Автор решения: am233dmg

Используйте BigInteger (для целочисленных данных) или BigDecimal(для чисел с плавающей точкой) для работы с очень большими числами:

public class Main {

    public static void main(String[] args) {
        System.out.print("Введите n факториала: ");
        Scanner read = new Scanner(System.in);
        int n = read.nextInt();
        System.out.print(n + "! = " + fact(BigInteger.valueOf(n), BigInteger.ONE).toString());
    }

    public static BigInteger fact(BigInteger number, BigInteger result) {
        if (number.compareTo(BigInteger.ZERO) < 0){
            return BigInteger.ZERO;
        }else  if (number.equals(BigInteger.ZERO)){
            return BigInteger.ONE;
        } else if (number.equals(BigInteger.ONE)) {
            return result;
        } else {
            return fact(number.subtract(BigInteger.ONE), number.multiply(result));
        }
    }

}
→ Ссылка