If you’re learning Java, understanding how to calculate the factorial of a number is a fundamental skill. Whether you’re preparing for exams, interviews, or just honing your coding skills, this guide will walk you through writing a factorial program in Java. We’ll use simple language, practical examples, and even include practice questions to test your knowledge. Let’s dive in!
A factorial of a number n (written as n!) is the product of all positive integers from 1 to n. For example:
Factorials grow quickly and are used in math, probability (permutations/combinations), and algorithms.
There are three common ways to calculate factorials in Java:
Let’s explore each method with code examples.
This method uses a for
loop to multiply numbers from 1 to n.
```java
public class Factorial {
public static void main(String[] args) {
int n = 5;
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i; // Multiply result by each number from 1 to n
}
System.out.println(n + "! = " + result); // Output: 5! = 120
}
}
Explanation:
result = 1
.result
by each number.A recursive function calls itself until it reaches the base case (n = 0 or n = 1).
public class FactorialRecursive {
public static void main(String[] args) {
int n = 5;
System.out.println(n + "! = " + factorial(n)); // Output: 5! = 120
}
static int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive call
}
}
}
Explanation:
For numbers beyond n = 20 (where results exceed long
limits), use BigInteger
.
import java.math.BigInteger;
public class FactorialBigInteger {
public static void main(String[] args) {
int n = 30;
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
System.out.println(n + "! = " + result); // Output: 30! = 265252859812191058636308480000000
}
}
Why use this?
Imagine you’re writing a program to calculate permutations (arrangements of items). For 5 books on a shelf, the number of ways to arrange them is 5! = 120. This is why factorials are crucial in algorithms!
Test your skills with these exercises (solutions at the end):
Use BigInteger
class to avoid integer overflow issues.
Recursion uses function calls, which can be slower and risk stack overflow. Iteration uses loops and is generally safer for large n.
Both approaches have O(n) time complexity since they perform n multiplications.
No, factorials are defined only for non-negative integers.
Try coding these examples yourself, and experiment with the practice questions.