HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

3 Ways to Calculate Factorial in Java

By Lokesh Gupta | Filed Under: Puzzles

Writing a program to calculate factorial in java – can be a coding exercise during java interviews. It’s always better to have idea of how to build such factorial program. Let’s go through such three ways:

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 pair a and b – 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.

Happy Learning !!

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Feedback, Discussion and Comments

  1. A. Coder

    August 1, 2018

    Why should the perfomance of the first method be better than the second one? It follows the dynamic programming method, one calculates the partial results with the space of one variable and the iteration variable. Yes each time the <-Test has to be resolved, but thats much "cheaper" than to initiate the function/method each time, create the new parameterset on the stack and generating more memory until the last factorial is resolved.

    Reply
  2. Ravichandra Enaganti

    April 22, 2016

    The third one uses streams and the second one uses recursion. You interchanged them.

    Reply

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Help me fight spammers. Solve this simple math. *

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

Java Puzzles

  • Interview Puzzles List
  • Dead vs Unreachable Code
  • Palindrome Number
  • Detect infinite loop in LinkedList
  • [i += j] Vs [i = i + j]
  • HiLo Guessing Game
  • Find All Distinct Duplicate Elements
  • TreeMap Put Operation
  • String With Nth Longest Length
  • Good String Vs Bad String
  • Complete String
  • Reverse String
  • Calculate Factorial
  • FizzBuzz Solution
  • Find Missing Number From Series
  • Create Instance Without New Keyword

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap