4 Ways to Calculate Factorial in Java
1) Calculate Factorial Using Iteration
Simple and most basic version. Good to know but not right to use for performance reason.
public static long factorialIterative ( long n ) { long r = 1 ; for ( long i = 1 ; i <= n; i++ ) { r*=i; } return r; } |
2) Calculate Factorial Using Recursion
If you are working on java 7 or lower version, then it is your best option. A well accepted answer as well. It uses recursion to calculate factorial.
public static long factorialRecursive( long n ) { return n == 1 ? 1 : n * factorialRecursive( n- 1 ); } |
3) Calculate Factorial Using Streams [Java 8]
Java 8 has support for streams which you can use to calculate factorial in mlst effective manner as below.
public static long factorialStreams( long n ) { return LongStream.rangeClosed( 1 , n ) .reduce( 1 , ( long a, long b ) -> a * b); } |
- Here,
LongStream.rangeClosed(2, n)
method creates a Stream of longs with the content[2, 3, ... , n]
. reduce (a, b) -> a * b
means that each paira
andb
– multiply them and return the result. The result then carries over to a for the next round.- The value “1” used in the reduced method is used as a starting value for variable
a
for the very first iteration.
4) Calculate Factorial for Numbers Greater than 20 using BigInteger
If you run any of above examples for numbers > 20; you will get incorrect output due to limitations of
long
datatype.System.out.println(getFactorial(20)); // 2432902008176640000 System.out.println(getFactorial(21)); // -4249290049419214848
Values just get bigger than what
long
can hold. The BigInteger
class allocates as much memory as it needs to hold all the bits of data it is asked to hold. Obviously if that much memory is preset in system, then only.
Now you will need
BigInteger
to hold more bigger values and use below code to get factorial.public static BigInteger getFactorial( int num) { BigInteger result = BigInteger.ONE; for ( int i = 1 ; i <= num; i++) result = result.multiply(BigInteger.valueOf(i)); return result; } |
Now you can get factorial of any number no matter how large it is.
System.out.println(getFactorial(22)); // 1124000727777607680000 System.out.println(getFactorial(32)); // 263130836933693530167218012160000000 System.out.println(getFactorial(132)); // Indeed a very long number is printed - Try yourself.