Java Program to Find Factorial of a Number

Example 1: Find Factorial of a number using for loop

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

Output

Factorial of 10 = 3628800

Example 2: Find 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);
    }
}

Output

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

Output

Factorial of 5 = 120

Leave a Reply