Calculate factorial of a Number in Java Example

This example shows how to calculate factorial of a number in Java using for loop (non-recursive), using recursion, and calculating factorial for large numbers using the BigInteger class.

What is the factorial of a number?

Definition of factorial from Wikipedia,

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

In mathematics, a product is a result of multiplying.

For example, factorial of 4 (denoted by 4!) is 4 x 3 x 2 x 1 = 24.

How to calculate the factorial of a number in Java?

The factorial of a number can be calculated in two ways, using for loop (non-recursive) method or using the recursion.

Using for loop

The factorial of a number can be calculated using for loop as given in the below example.

Output

Using recursion

The factorial of a number can be calculated using the recursive method as given below.

Output

How to calculate factorial of large numbers?

Let’s try to calculate factorial of 50 using the above program.

Output

The result is 0. How did that happen? Well, the factorial of 50 has 12 zeros at the end which is more than an int can hold (the int is 32 bit signed value in Java) so converting it to int value gives us zero.

In order to calculate the factorial of a large number, we need to use the BigInteger class as given below.

Output

This example is a part of the Java Basic Examples.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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