Java Program to Find Factorial of a Number
The factorial of a non-negative integer n is the product of all positive integers from 1 through n. It is written as n!. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. By definition, 0! = 1.
In Java, you can calculate a factorial with a while loop, a for loop, or recursion. The best numeric type depends on how large the input can be, because factorial values grow quickly.
The following picture shows the factorial formula and examples for the numbers 5 and 7.
Factorial Rules to Handle in a Java Program
0! = 1.- For a positive integer, multiply all integers from
1to that number. - A factorial is normally defined here only for non-negative integers, so a program should reject negative input.
- An
intcan store exact factorial values only through12!. Alongcan store them only through20!. UseBigIntegerfor larger factorials such as100!.
Example 1 – Factorial using While Loop
In this example, we shall make use of Java While Loop, to find the factorial of a given number.
While-loop factorial algorithm
We shall implement the following factorial algorithm with while loop.
- Start.
- Take number in a variable n. [We have to find factorial for this number.]
- Initialize variable factorial with
1. - Initialize loop control variable i with
1. - Check if i is less than or equal to n. If the condition is false, go to step 8.
- Multiply factorial with i.
- Increment i. Go to step 5.
- Print factorial.
- Stop.
Java Program
/**
* Java Program - Factorial
* Factorial of n is n! = 1.2.3....(n-1).n
* n should be >= 0
*/
public class Factorial {
public static void main(String[] args) {
//number
int n = 5;
//store factorial in this
int factorial = 1;
//compute factorial
int i=1;
while(i<=n) {
factorial *= i; //factorial = factorial * i
i++;
}
System.out.print(n+"! = "+factorial);
}
}
Run the above Java program, and you shall get the following output.
5! = 120
The variable factorial starts at 1. Each iteration multiplies it by the current value of i. For n = 5, its values become 1, 2, 6, 24, and finally 120.
Example 2 – Factorial using For Loop
In this example, we shall use Java For Loop to find the factorial of a given number. The algorithm would be same as that of the one used in above example.
Java Program
/**
* Java Program - Factorial
* Factorial of n is n! = 1.2.3....(n-1).n
* n should be >= 0
*/
public class Factorial {
public static void main(String[] args) {
//number
int n = 5;
//store factorial in this
int factorial = 1;
//compute factorial
for(int i=1;i<=n;i++) {
factorial *= i; //factorial = factorial * i
}
System.out.print(n+"! = "+factorial);
}
}
Run the above program, and you shall get the following output for n=5.
5! = 120
A for loop is a compact choice when the input is already available and the loop simply needs to run from 1 through n. With n = 0, the loop does not execute and the initial value 1 is correctly retained.
Example 3 – Factorial using Recursion
Finding Factorial of a number is a classic example for recursion technique in any programming language.
In this example, we shall use recursion and the factorial.
Java Program
/**
* Java Program - Factorial
* Factorial of n is n! = 1.2.3....(n-1).n
* n should be >= 0
*/
public class Factorial {
public static void main(String[] args) {
//number
int n = 5;
System.out.print(n+"! = "+factorial(n));
}
/**
* Computes Factorial of a number recursively
*/
static int factorial(int n) {
if (n==0) {
return 1;
} else {
return n*factorial(n-1);
}
}
}
Following is the output to this Java program.
5! = 120
The recursive method uses n == 0 as its base case. Otherwise, it evaluates n * factorial(n - 1). For example, factorial(5) reduces toward factorial(0), then the returned values are multiplied on the way back. Do not pass a negative value to this implementation because it never reaches the n == 0 base case.
Example 4 – Factorial using Ternary Operator
When using recursion technique, instead of if else as in above example, you can also use ternary operator.
In this example, we shall use recursion technique with ternary operator to make the code concise.
Java Program
/**
* Java Program - Factorial
* Factorial of n is n! = 1.2.3....(n-1).n
* n should be >= 0
*/
public class Factorial {
public static void main(String[] args) {
//number
int n = 5;
System.out.print(n+"! = "+factorial(n));
}
/**
* Computes Factorial of a number recursively and uses ternary operator
*/
static int factorial(int n) {
return (n == 0) ? 1 : n * factorial(n - 1);
}
}
Run the program to find factorial of 5. You can use the factorial() , from the above program, function in your program and call it, to find the factorial of any given n.
5! = 120
Factorial in Java using Scanner Input
If the number should be entered at runtime, read it with Scanner, check that it is non-negative, and then calculate the factorial. The following version uses long, so it is suitable for inputs from 0 through 20.
import java.util.Scanner;
public class FactorialScanner {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Factorial is not defined for negative integers.");
} else if (n > 20) {
System.out.println("Use BigInteger for values greater than 20.");
} else {
long factorial = 1;
for (int i = 2; i <= n; i++) {
factorial *= i;
}
System.out.println(n + "! = " + factorial);
}
scanner.close();
}
}
For an input of 7, the program prints:
Enter a non-negative integer: 7
7! = 5040
Factorial in Java using a Command-Line Argument
You can also pass the number when starting the Java program. This avoids Scanner and is useful when the value comes from a script or command line.
public class FactorialFromArgs {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FactorialFromArgs <non-negative integer>");
return;
}
int n = Integer.parseInt(args[0]);
if (n < 0) {
System.out.println("Factorial is not defined for negative integers.");
return;
}
if (n > 20) {
System.out.println("Use BigInteger for values greater than 20.");
return;
}
long factorial = 1;
for (int i = 2; i <= n; i++) {
factorial *= i;
}
System.out.println(n + "! = " + factorial);
}
}
Compile the class and pass the number as the first command-line argument:
javac FactorialFromArgs.java
java FactorialFromArgs 5
5! = 120
How to Find 100 Factorial in Java with BigInteger
100! is far larger than the maximum value of both int and long. Java’s BigInteger class can represent integers with arbitrary precision, limited by available memory, so it is the appropriate type for factorials such as 100!.
import java.math.BigInteger;
public class FactorialBigInteger {
public static void main(String[] args) {
int n = 100;
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.println(n + "! = " + factorial);
}
}
The exact value produced for 100! is:
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Why Java Factorial Results Overflow with int or long
Java integer types have fixed ranges. When multiplication exceeds the range of the chosen type, integer overflow occurs and the result is no longer the mathematical factorial. Java does not automatically switch an overflowing int or long to BigInteger.
12! = 479001600fits in anint, but13!does not.20! = 2432902008176640000fits in along, but21!does not.- For factorials beyond
20!, useBigIntegerif the exact integer result is required.
Choosing Between Loop, Recursion, and BigInteger for Java Factorials
For ordinary factorial calculations, a loop is simple and avoids recursive call-stack growth. Recursion is useful for demonstrating the mathematical definition n! = n × (n - 1)!, provided a correct base case and validated non-negative input are used. The numeric type is a separate decision: use int only through 12!, long only through 20!, and BigInteger for larger exact factorials.
In this Java Tutorial, we learned how to write Java programs to find the factorial of a given number using loop statements and recursion technique.
TutorialKart.com