Calculate Factorial of a Given Number in Java
This program calculates the factorial of a given number using recursion in Java. The factorial of a number n
is the product of all positive integers less than or equal to n
. It is denoted by n!
and is defined as:
n! = n * (n - 1) * (n - 2) * ... * 1
For example:
5! = 5 * 4 * 3 * 2 * 1 = 120
3! = 3 * 2 * 1 = 6
0! = 1
(by definition)
Java Program
/**
* This class contains a method to calculate the factorial of a given number.
*/
public class FactorialCalculator {
/**
* This method calculates the factorial of a given number using recursion.
* @param n The number for which the factorial is to be calculated. Must be a non-negative integer.
* @return The factorial of the given number.
*/
public static long factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive case: n! = n * (n - 1)!
return n * factorial(n - 1);
}
public static void main(String[] args) {
// Example usage of the factorial method
int number = 5;
long result = factorial(number);
System.out.println("The factorial of " + number + " is " + result);
}
}
Explanation
The program consists of the following parts:
- FactorialCalculator Class: This class contains the method to calculate the factorial.
factorial(int n)
: This method is a recursive function that calculates the factorial of a given number. It has one parametern
, which is the number for which the factorial is to be calculated.main(String[] args)
: This is the main method where the program execution begins. It calls thefactorial
method and prints the result.
- factorial Method: This method uses recursion to calculate the factorial.
- Base Case: If
n
is 0, the method returns 1, because by definition,0! = 1
. - Recursive Case: If
n
is greater than 0, the method returnsn
multiplied by the factorial ofn - 1
(n!
=n * (n - 1)!
).
- Base Case: If
How to Run the Program
To run this program, follow these steps:
-
- Save the code to a file named
FactorialCalculator.java
. - Open a terminal and navigate to the directory containing the file.
- Compile the program using the following command:
- Save the code to a file named
javac FactorialCalculator.java
-
- Run the compiled program using the following command:
java FactorialCalculator
The program will output the factorial of the number specified in the main
method.