Java Program to Find the Factorial of a Number
The factorial of a whole number n, written n!, is the product of all positive whole numbers from 1 to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. By definition, 0! = 1. Factorials are not defined for negative numbers.
Factorials grow very fast. 12! is the largest that fits in an int, and 20! is the largest that fits in a long, so this page uses long and, for bigger values, BigInteger.
1. Factorial Using a for Loop
Start with factorial = 1 and multiply it by every number from 1 to n.
public class Factorial {
public static void main(String[] args) {
int n = 5;
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println("Factorial of " + n + " = " + factorial);
}
}
Factorial of 5 = 120
2. Factorial Using a while Loop and User Input
This version counts down from n with a while loop and rejects negative input.
import java.util.Scanner;
public class FactorialWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
scanner.close();
if (n < 0) {
System.out.println("Factorial is not defined for negative numbers.");
return;
}
long factorial = 1;
int i = n;
while (i > 1) {
factorial *= i;
i--;
}
System.out.println("Factorial of " + n + " = " + factorial);
}
}
Enter a number: 10 Factorial of 10 = 3628800
Enter a number: -3 Factorial is not defined for negative numbers.
3. Factorial Using Recursion
A recursive method calls itself. Since n! = n × (n - 1)!, the method returns n * factorial(n - 1). The base case stops the calls: when n is 0 or 1, it returns 1.
public class FactorialRecursion {
static long factorial(int n) {
if (n <= 1) {
return 1; // base case
}
return n * factorial(n - 1); // recursive case
}
public static void main(String[] args) {
for (int n = 0; n <= 6; n++) {
System.out.println(n + "! = " + factorial(n));
}
}
}
0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720
4. Factorial of Large Numbers Using BigInteger
For numbers above 20, long overflows and gives wrong results. java.math.BigInteger has no upper limit, so it can hold the exact value of 30! or even 1000!.
import java.math.BigInteger;
public class FactorialBig {
public static void main(String[] args) {
int n = 30;
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.println(n + "! = " + factorial);
}
}
30! = 265252859812191058636308480000000
5. Summary
n!is the product 1 × 2 × ... × n, and 0! is 1.- Start the result at 1 and multiply in a
fororwhileloop. - A recursive solution returns
n * factorial(n - 1)with a base case for 0 and 1. longholds factorials only up to 20!; useBigIntegerfor larger values.