Java Factorial Program using Scanner

In this post, we show how to create a Java program to find Factorial of a given number. There is lot's of Factorial Programs out there on the internet using loops, recursive but here I use BigInteger.multiply() method to find Factorial of a given number.
Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!.
For example:
4! = 4*3*2*1 = 24  
5! = 5*4*3*2*1 = 120  

Java Factorial Program

In the below program, we are using a Scanner to get input from the console.
import java.math.BigInteger;
import java.util.Scanner;

public class FactorialExample {

    public static void main(String[] args) {

     Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int n = scanner.nextInt();
        BigInteger fact = factorial(n);

        System.out.printf("%d! is %d", n, fact);
        
        scanner.close();
    }

    private static BigInteger factorial(int value) {

     BigInteger result = BigInteger.ONE;

        if (value != 0 && value != 1) {

            for (int i = 2; i <= value; i++) {

                result = result.multiply(BigInteger.valueOf(i));
            }
        }

        return result;
    }
}
Output:
Enter a number: 5

5! is 120
There are different techniques to write this program, check out this article.

Related Java Programs


Comments