0
0
JavaProgramBeginner · 2 min read

Java Program to Find Factorial of a Number

You can find the factorial of a number in Java by using a loop to multiply all integers from 1 to that number, like for (int i = 1; i <= n; i++) result *= i;.
📋

Examples

Input0
OutputFactorial of 0 is 1
Input5
OutputFactorial of 5 is 120
Input10
OutputFactorial of 10 is 3628800
🧠

How to Think About It

To find the factorial of a number, think of multiplying all whole numbers from 1 up to that number. For example, factorial of 5 means 1 × 2 × 3 × 4 × 5. We start with 1 and keep multiplying by each number until we reach the input number.
📐

Algorithm

1
Get input number n
2
Set result to 1
3
For each number i from 1 to n, multiply result by i
4
After the loop ends, return or print the result
💻

Code

java
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();
    }
}
Output
Enter a number: 5 Factorial of 5 is 120
🔍

Dry Run

Let's trace the input 5 through the code

1

Input number

User enters n = 5

2

Initialize result

result = 1

3

Loop iteration 1

i = 1, result = 1 * 1 = 1

4

Loop iteration 2

i = 2, result = 1 * 2 = 2

5

Loop iteration 3

i = 3, result = 2 * 3 = 6

6

Loop iteration 4

i = 4, result = 6 * 4 = 24

7

Loop iteration 5

i = 5, result = 24 * 5 = 120

8

End loop and print

Print 'Factorial of 5 is 120'

iresult
11
22
36
424
5120
💡

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

Recursion
java
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();
    }
}
Uses function calling itself; elegant but can cause stack overflow for very large n.
Using Java Streams
java
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();
    }
}
Uses Java 8 streams for a functional style; concise but less intuitive for beginners.

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.

ApproachTimeSpaceBest For
Iterative loopO(n)O(1)Most efficient and simple
RecursionO(n)O(n)Elegant but risks stack overflow
Java StreamsO(n)O(1)Functional style, less beginner-friendly
💡
Use a long variable to store factorial because results grow very fast and can exceed int limits.
⚠️
Starting the loop from 0 instead of 1, which causes the factorial to always be zero.