Java Program to find the factorial of a given number.
Objective
Write a Java program to calculate the factorial of a user-provided integer.
Algorithm / Approach
- Prompt the user to input a positive integer
n. - Initialize an integer variable
resto 1 (this will store the result). - Start a
forloop fromi = ndown to 2. - In each iteration, multiply
resbyi(res = res * i). - After the loop completes, print
res.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
int n,res=1;
Scanner s=new Scanner(System.in);
System.out.print("Enter a Num: ");
n = s.nextInt();
for(int i=n; i>=2;i--) {
res = res*i;
}
System.out.print("Result = "+res);
}
}
Expected Output
Enter a Num: 5 Result = 120
Explanation of the Program
- The factorial of a number N (denoted as N!) is the product of all positive integers less than or equal to N.
- The loop decrements from
ndown to 2, repeatedly multiplying the running total. - We can stop at 2 because multiplying by 1 does not change the result.
- The
resvariable must be initialized to 1. If it were initialized to 0, every multiplication would yield 0.
Complexity
Time Complexity
O(n) - The loop runs n times.
Space Complexity
O(1)
Common Mistakes
- Initializing the result variable
resto 0 instead of 1. - Not handling inputs of 0 (since 0! = 1, the loop condition fails, and it correctly prints the initialized value 1).