[Java] Factorial of a Number by Java Program

The Factorial of number is denoted by n! , is the product/multiplication of all positive integers less than or equal to n.

Where n is always a non-negative number and The value of 0! is 1, according to the convention for an empty product.

Example :

0!=1=1
1!=1=1
5!=5 * 4 * 3 * 2 * 1=120
12!=12 * 11 * 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1=479001600

Below are examples to calculate factorial of  a Number. I have consider all the cases like calculation of big factorial number by loop and also through recursion.

Factorial of a Number by using Java code loop.

class Factorial {
public static void main(String args[]) {
int n, c, fact = 1;

System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);

n = in.nextInt();

if (n < 0)
System.out.println("Number should be non-negative.");
else {
for (c = 1; c <= n; c++)
fact = fact * c;

System.out.println("Factorial of " + n + " is = " + fact);
}
}
}

Factorial of a Big Integer Number by using loop

If calculation of number is too big which cross the Integer limit then use BigInteger instead if Integer.

class Factorial {
public static void main(String args[]) {
int n, c;
BigInteger inc = new BigInteger("1");
BigInteger fact = new BigInteger("1");

Scanner input = new Scanner(System.in);

System.out.println("Input an integer");
n = input.nextInt();

for (c = 1; c <= n; c++) {
fact = fact.multiply(inc);
inc = inc.add(BigInteger.ONE);
}

System.out.println(n + "! = " + fact);
}
}

Factorial of Integer Number by using Java Recursion.

import java.util.Scanner;

public class FactorialByRecursion {

public static void main(String[] args) {
int n;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);

n = in.nextInt();

if (n < 0)
System.out.println("Number should be non-negative.");
else {
System.out.println("Factorial of " + n + " is = " + factorial(n));
}

}

private static int factorial(int num)
{
//Recursion Terminating condition if 0 terminate with value 1
if(num==0)
return 1;
else
return num*factorial(num-1);
}

}

More Info

For more Algorithms and Java Programing Test questions and sample code follow below links