Java Program to Find Factorial of a Number
for (int i = 1; i <= n; i++) result *= i;.Examples
How to Think About It
Algorithm
Code
import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int n = scanner.nextInt(); long result = 1; for (int i = 1; i <= n; i++) { result *= i; } System.out.println("Factorial of " + n + " is " + result); scanner.close(); } }
Dry Run
Let's trace the input 5 through the code
Input number
User enters n = 5
Initialize result
result = 1
Loop iteration 1
i = 1, result = 1 * 1 = 1
Loop iteration 2
i = 2, result = 1 * 2 = 2
Loop iteration 3
i = 3, result = 2 * 3 = 6
Loop iteration 4
i = 4, result = 6 * 4 = 24
Loop iteration 5
i = 5, result = 24 * 5 = 120
End loop and print
Print 'Factorial of 5 is 120'
| i | result |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
Why This Works
Step 1: Start with 1
We use result = 1 because multiplying by 1 does not change the value and it is the identity for multiplication.
Step 2: Multiply in loop
The for loop multiplies result by each number from 1 to n, building the factorial step by step.
Step 3: Print final result
After the loop, result holds the factorial, which we print to show the answer.
Alternative Approaches
import java.util.Scanner; public class Factorial { public static long factorial(int n) { if (n <= 1) return 1; else return n * factorial(n - 1); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int n = scanner.nextInt(); System.out.println("Factorial of " + n + " is " + factorial(n)); scanner.close(); } }
import java.util.Scanner; import java.util.stream.LongStream; public class Factorial { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int n = scanner.nextInt(); long result = LongStream.rangeClosed(1, n).reduce(1, (a, b) -> a * b); System.out.println("Factorial of " + n + " is " + result); scanner.close(); } }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n once, so the time grows linearly with n.
Space Complexity
Only a few variables are used, so space is constant regardless of n.
Which Approach is Fastest?
The iterative loop is fastest and safest; recursion adds overhead and risk of stack overflow; streams are elegant but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(n) | O(1) | Most efficient and simple |
| Recursion | O(n) | O(n) | Elegant but risks stack overflow |
| Java Streams | O(n) | O(1) | Functional style, less beginner-friendly |