Factorial Calculation with Varargs in Java
Write a Java program demonstrating a method with varargs that calculates the factorial of integers
- The FactorialCalculator class contains a static method named calculateFactorial that takes a variable number of integers (int... numbers) as arguments.
- Inside the method, it initializes a result variable to store the product of factorials, initially set to 1.
- It then iterates through each number in the numbers array using an enhanced for loop.
- For each number, it calculates its factorial by iterating from 1 up to the number itself (i <= num) and multiplying the current value of result by i.
- After calculating the factorial for each number, it returns the final result, which is the product of all factorials.
- In the main method, the calculateFactorial method is called with the numbers 2, 3, and 5.
- The calculated factorial is then printed to the console.
Source Code
public class FactorialCalculator
{
static long calculateFactorial(int... numbers)
{
long result = 1;
for (int num : numbers)
{
for (int i = 1; i <= num; i++)
{
result *= i;
}
}
return result;
}
public static void main(String[] args)
{
long factorial = calculateFactorial(2, 3, 5);
System.out.println("Factorial : " + factorial);
}
}
Output
Factorial : 1440