Find Factorial of a Number using Java

we’ll talk about find the factorial of a number using for and while loop in Java.

Now, we’ll talk about find the factorial of a number using for and while loop in Java. There will be three examples to discuss. Before, we go to see our program. You need to know about factorial number. See below to see the factorial of a positive number n:

factorial of n (n!) = 1 * 2 * 3 * 4 * … * n

Example 1: Find Factorial of a Number using for loop in Java

public class Factorial {
    public static void main(String[] args) {
        int num = 10;
        long factorial = 1;
        for(int i = 1; i <= num; ++i)
        {
            // factorial = factorial * i;
            factorial *= i;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

The output will be:

Factorial of 10 = 3628800

The program used for loop to loop through all numbers between 1 and the given number num (10), and the product of each number till num is stored in a variable factorial. store large results of factorial, we used long instead of int. However, it’s still not big enough to store the value of bigger numbers (say 100).

For results that cannot be stored in a long variable, we use BigInteger variable declared in java.math library in the example and we have to use multiply for the product.

Example 2: Find Factorial of a number using BigInteger in Java

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);
    }
}

The output will be:

Factorial of 30 = 265252859812191058636308480000000

Example 3: Find Factorial of a number using while loop

public class Factorial {
    public static void main(String[] args) {
        int num = 5, i = 1;
        long factorial = 1;
        while(i <= num)
        {
            factorial *= i;
            i++;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}

The output will shown like below:

Factorial of 5 = 120

For another java tutorial, you can find it more through this link.

Close