Skip to content

Calculate factorial of a Number in Java Example

Calculate factorial of a Number 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 a for loop (non-recursive) method or using the recursion.

Using for loop

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

Output

Using recursion

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

Output

How to calculate factorial of large numbers?

Let’s try to calculate a 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

Leave a Reply

Your email address will not be published.