Use BigInteger to prevent overflow in factorial calculation by VanshSharma3 · Pull Request #7358 · TheAlgorithms/Java
- I have read CONTRIBUTING.md.
- All filenames are in PascalCase.
- This pull request is all my own work -- I have not plagiarized it.
- All functions and variable names follow Java naming conventions.
- All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- All new algorithms include a corresponding test class that validates their functionality.
- All new code is formatted with
clang-format -i --style=file path/to/your/file.java
Description
Updated the Factorial.java implementation to use BigInteger instead of long.
Reason for change:
The previous implementation using long would overflow for any input $n > 20$. Since factorials grow exponentially, BigInteger is necessary to handle arbitrarily large results accurately without data loss.
Changes:
- Changed return type to
BigInteger. - Updated the iterative loop to use
BigInteger.multiply(). - Added a check for negative input to throw
IllegalArgumentException.