It is necessary to calculate the factorial of a number.
When the result is too large, it goes beyond long or int .

What can be done in this case?

 int n = 101; long res = n; int count = n - 1; do { res *= count; count--; } while (count > 0); System.out.println(res); 
  • case, case, to do - etki

3 answers 3

Use the BigDecimal or BigInteger class. Well, what is the factorial without recursion :)

 public static BigInteger getFactorial(BigInteger num) { if (num.intValue() == 0) return BigInteger.valueOf(1); if (num.intValue() == 1) return BigInteger.valueOf(1); return num.multiply(getFactorial(num.subtract(BigInteger.valueOf(1)))); } 
  • one
    I also first wrote about BigDecimal, but, as far as it can be assumed from the description, on large numbers he will begin to openly lie, providing only multiples of ten. As far as I understand, BigInteger is needed, and, of course, not only by reference, but also by the description of working with it. - etki
  • Cosmic numbers are always in trouble. - Sergey Mitrofanov
  • @Etki who begins to lie frankly? BigInteger? Special class for working with long arithmetic? - Andrew Bystrov
  • @AndrewBystrov BigDecimal. If I understood the dock correctly, then it is stored integer * (10 ^ integer), which for large numbers (more, for example, Integer.MAX_VALUE), will lead to loss of accuracy. Of course, I could be wrong. - etki

Use arrays, not just a variable, and hand carry digits.

  • Yes, I agree ... you can and so - Vladislav Pyatkov
  • one
    As an academic exercise, yes. Strings or arrays. - Sergey Mitrofanov

Another option is to use BigInteger and add values ​​to an ArrayList. With a large number of calculations, this becomes more efficient than recursion.