The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n.
Factorials are widely used in mathematics, particularly in permutations, combinations, and other areas of combinatorial analysis.
Understanding how to compute the factorial of a number is a fundamental skill in programming, as it introduces concepts
such as recursion and iterative processing.
Objective
The objective of this program is to provide a simple Java implementation that calculates the factorial of a given
non-negative integer input by the user. This program will illustrate both iterative and recursive approaches to solve
the factorial calculation problem.
Java Code
import java.util.Scanner;
public class FactorialCalculator {
// Method to calculate factorial iteratively
public static long factorialIterative(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// Method to calculate factorial recursively
public static long factorialRecursive(int n) {
if (n == 0) {
return 1;
}
return n * factorialRecursive(n - 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
if (number < 0) {
System.out.println("Factorial is not defined for negative integers.");
} else {
long iterativeResult = factorialIterative(number);
long recursiveResult = factorialRecursive(number);
System.out.println("Factorial of " + number + " (Iterative): " + iterativeResult);
System.out.println("Factorial of " + number + " (Recursive): " + recursiveResult);
}
scanner.close();
}
}
Program Structure and Execution
The program consists of a class named FactorialCalculator
that contains two methods for calculating factorials:
factorialIterative
and factorialRecursive
. The main method is where the program execution begins.
Here’s a brief overview of its structure:
- factorialIterative(int n): This method computes the factorial of a number using a loop.
- factorialRecursive(int n): This method computes the factorial using recursion.
- main(String[] args): This is the entry point of the program. It prompts the user for input,
checks if the input is valid, and then calls both methods to display the results.
How to Run the Program
- Ensure you have Java Development Kit (JDK) installed on your computer.
- Open a text editor or Integrated Development Environment (IDE) and create a new file named
FactorialCalculator.java
. - Copy and paste the provided Java code into the file.
- Open a terminal or command prompt.
- Navigate to the directory where the file is saved.
- Compile the program using the command:
javac FactorialCalculator.java
. - Run the program using the command:
java FactorialCalculator
. - Follow the prompts to enter a non-negative integer and see the factorial computed by both methods.