Calculate Factorial in Java: Solution, Explanation & Practice
Calculate factorial of a number
Problem summary
Write a program that calculates n! (factorial). Your code should work for any non-negative integer.
Starter code
public class Main {
public static void main(String[] args) {
int n = 5; // Test case 1
// Calculate n! = n * (n-1) * ... * 1
// Print: Factorial: <result>
}
}Expected output and test cases
- 5! = 120
Factorial: 120
- 4! = 24
Factorial: 24
- 0! = 1
Factorial: 1
Hints
- Start from 1 and multiply up to n
- Or start from n and multiply down to 1
- 0! is defined as 1
Validated solution
Reveal Java solution
public class Main {
static long factorial(int n) {
if (n < 0) throw new IllegalArgumentException("n must be non-negative");
long result = 1;
for (int value = 2; value <= n; value++) result *= value;
return result;
}
public static void main(String[] args) {
System.out.println("Factorial: " + factorial(5));
}
}How to approach the problem
Factorial is a product, so start at the multiplicative identity 1 and multiply each integer from 2 through n. The guard prevents a loop from quietly assigning a meaning to negative factorials.
Approach
- Reject negative input.
- Initialize result to 1 so 0! stays 1.
- Multiply each remaining factor exactly once.
Time and space complexity
Time: O(n). Space: O(1).
Edge cases to test
- 0! is 1.
- long overflows after 20!, so large exact values need BigInteger.
Common mistakes
- Starting at zero, which makes every result zero.
- Using int and assuming a positive result proves correctness.
Follow-up challenge
Implement factorial with BigInteger and compare iterative and recursive stack usage.
Related Core Java Basics exercises
- Practice Count Digits in Java
- Practice Calculate Power in Java
- Practice Palindrome Number Check in Java
Practice all Core Java Basics exercises · Run this idea in the Java compiler