Factorial
Java coding interview problem for Number Logic: Factorial.
The Factorial of a number is one of the most frequently asked Java coding interview questions. It helps interviewers evaluate your understanding of loops, arithmetic operations, recursion, and mathematical problem-solving.
Factorials are widely used in mathematics, combinatorics, probability, permutations, combinations, and algorithm analysis.
What is Factorial?
The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.
It is represented using the ! (factorial) symbol.
Mathematically,
n! = n × (n − 1) × (n − 2) × ... × 2 × 1
Examples
1! = 1
2! = 2 × 1 = 2
3! = 3 × 2 × 1 = 6
4! = 4 × 3 × 2 × 1 = 24
5! = 5 × 4 × 3 × 2 × 1 = 120
6! = 6 × 5 × 4 × 3 × 2 × 1 = 720
Special Case
One important mathematical rule is
0! = 1
Although it may seem unusual, this definition is essential in mathematics, combinatorics, and probability theory.
Factorial Table
| Number | Factorial |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
| 6 | 720 |
| 7 | 5040 |
| 8 | 40320 |
| 9 | 362880 |
| 10 | 3628800 |
Real Interview Question
Write a Java program to calculate the factorial of a given number.
Understanding the Logic
Suppose the input number is
5
The factorial is calculated as
5 × 4 × 3 × 2 × 1
Instead of writing every multiplication manually, we use a loop.
Each iteration multiplies the current result with the next integer.
Visual Representation
Input
5
Processing
result = 1
↓
result = 1 × 5 = 5
↓
result = 5 × 4 = 20
↓
result = 20 × 3 = 60
↓
result = 60 × 2 = 120
↓
result = 120 × 1 = 120
Output
120
Brute Force Approach
The simplest approach is
- Start with result = 1.
- Multiply the result by every number from 1 to n (or n to 1).
- Continue until all numbers are multiplied.
- Print the final result.
Algorithm
Step 1
Read the input number.
Step 2
Handle the special case.
If number == 0
Return 1
Step 3
Initialize
factorial = 1;
Step 4
Repeat from
1 to number
Step 5
Multiply
factorial = factorial * i;
Step 6
Continue until the loop ends.
Step 7
Print the factorial.
Dry Run
Input
5
Initial
factorial = 1
| Iteration | Current Number | Factorial |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 6 |
| 4 | 4 | 24 |
| 5 | 5 | 120 |
Output
120
Another Dry Run
Input
6
Initial
factorial = 1
| Iteration | Current Number | Factorial |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 6 |
| 4 | 4 | 24 |
| 5 | 5 | 120 |
| 6 | 6 | 720 |
Output
720
Approach 1 — Using Iteration (Loop)
This is the most common and interview-preferred solution because it is simple, efficient, and avoids recursion overhead.
Complete Java Program
public class FactorialExample {
public static void main(String[] args) {
int number = 5;
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial = factorial * i;
}
System.out.println("Factorial = " + factorial);
}
}
Output
Factorial = 120
Step-by-Step Code Explanation
Step 1
Declare the input number.
int number = 5;
Current value
5
Step 2
Initialize the factorial.
long factorial = 1;
Initially
factorial = 1
We use long instead of int because factorial values grow very quickly.
Step 3
Start the loop.
for (int i = 1; i <= number; i++)
The loop begins from
1
and continues until
number
Step 4
Multiply the result.
factorial = factorial * i;
Iteration by iteration
1 × 1 = 1
↓
1 × 2 = 2
↓
2 × 3 = 6
↓
6 × 4 = 24
↓
24 × 5 = 120
Step 5
Print the result.
System.out.println("Factorial = " + factorial);
Output
Factorial = 120
Example Execution
Input
4
Processing
factorial = 1
↓
1 × 1 = 1
↓
1 × 2 = 2
↓
2 × 3 = 6
↓
6 × 4 = 24
Output
Factorial = 24
Input
7
Processing
1 × 2 × 3 × 4 × 5 × 6 × 7
Output
5040
Why Does This Work?
The factorial operation is simply the repeated multiplication of consecutive positive integers.
By starting with
1
and multiplying each number from
1 to n
the loop gradually builds the final factorial value.
Each iteration contributes one multiplication, and after the final iteration, the variable contains the complete factorial.
Advantages of This Approach
- Easy to understand.
- Most commonly asked in Java interviews.
- Efficient and straightforward.
- Uses constant extra memory.
- Avoids recursion overhead.
- Suitable for beginners and production code.
Drawbacks
Although the iterative solution is the preferred interview approach, interviewers often ask follow-up questions such as:
- Can you solve it using recursion?
- What happens for very large numbers?
- Why does 13! overflow an
int? - When should you use BigInteger?
- What is the time and space complexity?
- Which approach is better: iteration or recursion?
In the next part, we'll cover:
- Recursive solution
- BigInteger approach for very large factorials
- Reusable method implementation
- Time and space complexity
- Iteration vs recursion comparison
- Common interview mistakes
- Frequently asked interview questions
- Related coding problems
- Key takeaways
- Interview tips
Approach 2 — Using Recursion
Recursion is another common interview solution.
In recursion, a method calls itself until it reaches a base condition.
For factorial,
n! = n × (n − 1)!
Base Condition
0! = 1
1! = 1
Recursive Formula
factorial(5)
=
5 × factorial(4)
=
5 × 4 × factorial(3)
=
5 × 4 × 3 × factorial(2)
=
5 × 4 × 3 × 2 × factorial(1)
=
5 × 4 × 3 × 2 × 1
=
120
Java Program
public class FactorialRecursion {
static long factorial(int number) {
if (number == 0 || number == 1) {
return 1;
}
return number * factorial(number - 1);
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial = " + factorial(number));
}
}
Output
Factorial = 120
Dry Run for Recursion
Input
4
Method Calls
factorial(4)
↓
4 × factorial(3)
↓
4 × 3 × factorial(2)
↓
4 × 3 × 2 × factorial(1)
↓
4 × 3 × 2 × 1
Result
24
Approach 3 — Using BigInteger
Factorial values grow extremely fast.
For example,
20! = 2,432,902,008,176,640,000
This value fits inside a long.
However,
21!
is larger than the maximum value that a long can store.
For such cases, Java provides the BigInteger class.
Java Program
import java.math.BigInteger;
public class BigIntegerFactorial {
public static void main(String[] args) {
int number = 50;
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= number; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.println(number + "! = " + factorial);
}
}
Output
50! =
30414093201713378043612608166064768844377641568960512000000000000
Approach 4 — Using a Reusable Method
Reusable methods improve
- Readability
- Maintainability
- Unit testing
- Code reuse
Java Program
public class FactorialMethod {
static long factorial(int number) {
long result = 1;
for (int i = 1; i <= number; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int number = 6;
System.out.println("Factorial = " + factorial(number));
}
}
Output
Factorial = 720
Time Complexity
Iterative Approach
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) |
Recursive Approach
| Operation | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) |
The recursive solution uses additional stack memory.
BigInteger Approach
| Operation | Complexity |
|---|---|
| Time | O(n × M) |
| Space | Depends on Number Size |
Where M is the cost of multiplying large numbers.
Comparison of All Approaches
| Approach | Time | Space | Recommended |
|---|---|---|---|
| Iteration | O(n) | O(1) | ✅ Best for Interviews |
| Recursion | O(n) | O(n) | Good for Understanding |
| BigInteger | O(n × M) | Variable | Large Numbers |
| Reusable Method | O(n) | O(1) | Production Ready |
Common Mistakes
Mistake 1
Initializing factorial as
long factorial = 0;
Wrong
0 × anything = 0
Always initialize
long factorial = 1;
Mistake 2
Ignoring
0!
Correct Answer
1
Many beginners incorrectly return
0
Mistake 3
Using int for large factorials.
Example
13!
overflows an int.
Use
long
or
BigInteger
for larger values.
Mistake 4
Missing the recursion base condition.
Wrong
return number * factorial(number - 1);
This causes infinite recursion and results in a
StackOverflowError
Always include
if (number == 0 || number == 1)
Mistake 5
Accepting negative numbers without validation.
Factorial is defined only for non-negative integers.
Example
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
}
Interview Follow-up Questions
Q1. Calculate factorial using recursion.
Q2. Calculate factorial without recursion.
Q3. Why is 0! equal to 1?
Q4. Why does 13! overflow an int?
Q5. When should BigInteger be used?
Q6. Find the trailing zeros in a factorial.
Q7. Calculate factorial for very large numbers.
Q8. Compare recursion and iteration.
Q9. Find nPr using factorial.
Q10. Find nCr using factorial.
Related Coding Problems
- Fibonacci Series
- Prime Number
- Reverse Integer
- Sum of Digits
- Power of a Number
- Decimal to Binary
- Binary to Decimal
- Trailing Zeros in Factorial
- Permutations and Combinations
Key Takeaways
- Factorial is the product of all positive integers from 1 to n.
- By definition, 0! = 1.
- The iterative approach is the most efficient and commonly asked in interviews.
- The recursive approach is elegant but uses additional stack memory.
- Use BigInteger when factorial values exceed the limits of
long. - The iterative solution runs in O(n) time with O(1) extra space.
- Factorial is widely used in permutations, combinations, probability, and algorithm analysis.
Interview Tip
If an interviewer asks:
"Write a Java program to calculate the factorial of a number."
Start with the iterative solution, as it is the most efficient and avoids recursion overhead. Explain why the factorial variable is initialized to 1, discuss the special case 0! = 1, and mention that int or long can overflow for large values. Finally, demonstrate deeper knowledge by explaining the recursive approach, when to use BigInteger, and the time and space complexity of each solution. This progression shows both practical coding skills and a strong understanding of Java fundamentals.