HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Puzzles / 3 Ways to Calculate Factorial in Java

3 Ways to Calculate Factorial in Java

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 !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

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.

  2. Ravichandra Enaganti

    April 22, 2016

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

Comments are closed on this article!

Search Tutorials

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

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

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

  • Sealed Classes and Interfaces