DEV Community

Om Bhusal
Om Bhusal

Posted on

Factorial Program in Java

Hey folks, today in this blog you’ll see Factorial Program in Java. I have created blogs on making a Group Chat APP Using JAVA and in this fantastic blog, you will learn how to create a Factorial Program in Java. So, Factorial Program in Java: Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!.For example:
6! = 720
7! = 5040

Image description

Here, 6! is pronounced as “6 factorial”, it is also called “6 bang” or “6 shrieks”.

The factorial is normally used in Combinations and Permutations (mathematics).

The factorial of a positive number n is given by:
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n

There are many ways to write the factorial program in java language. Let’s see the 3 ways to write the factorial program in java.

You might like this:

JavaScript Projects For Beginners
Automatic Image Slider
Sidebar Menu using HTML and CSS
Cool Glowing Effect on Buttons

Example 1: Find the Factorial of a number using BigInteger
`import java.math.BigInteger;

public class Factorial {

public static void main(String[] args) {

    int num = 30;
    BigInteger factorial = BigInteger.ONE;
    for(int i = 1; i <= num; ++i)
    {
        // factorial = factorial * i;
        factorial = factorial.multiply(BigInteger.valueOf(i));
    }
    System.out.printf("Factorial of %d = %d", num, factorial);
}
Enter fullscreen mode Exit fullscreen mode

}`

Here, instead of long, we use BigInteger variable factorial.

Since * cannot be used with BigInteger, we instead use multiply() for the product. Also, num should be cast to BigInteger not long for multiplication.

Discussion (0)