Introduction
A Brief on Factorial: Mathematical Context
A factorial, denoted as n!, of any non-negative integer n, is the product of all positive integers up to n. To illustrate, the factorial of 5 (5!) is calculated as 12345 = 120.
The Fundamentals of Factorial in Java
There are various strategies available in Java to perform factorial calculations, each with its unique benefits and drawbacks.
Method 1: Employing Iterative Approach
An iterative approach uses a straightforward for loop to compute the factorial.
public class Main {
public static void main(String[] args) {
int num = 5;
long factorial = 1;
for(int i = 1; i <= num; i)
{
factorial *= i;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}
Method 2: The Recursive Approach
Recursion is another common technique for executing factorial calculations in Java.
public class Main {
public static long factorial(int n) {
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]) {
int i;
long fact = 1;
int number = 5; // number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of " number " is: " fact);
}
}
Method 3: Utilizing Stream API
The Stream API, introduced in Java 8, is another effective method for factorial calculations.
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int num = 5;
System.out.printf("Factorial of %d = %d", num, factorial(num));
}
public static long factorial(int num) {
return IntStream.rangeClosed(1, num).reduce(1, (x, y) -> x * y);
}
}
Factorial and BigInteger Class
To calculate factorials for larger numbers, Java’s BigInteger class comes in handy.
import java.math.BigInteger;
public class Main {
static BigInteger factorial(int N) {
BigInteger f = new BigInteger("1");
for (int i = 2; i <= N; i )
f = f.multiply(BigInteger.valueOf(i));
return f;
}
public static void main(String args[]) throws Exception {
int N = 20;
System.out.println(factorial(N));
}
}
Factorial in Multi-threaded Environment
Java’s Fork/Join Framework allows factorial calculations to be executed in a multi-threaded environment.
import java.util.concurrent.RecursiveTask;
public class FactorialTask extends RecursiveTask<Integer> {
private final int n;
public FactorialTask(int n) {
this.n = n;
}
@Override
protected Integer compute() {
if (n <= 1) {
return 1;
} else {
FactorialTask subtask = new FactorialTask(n - 1);
subtask.fork();
return n * subtask.join();
}
}
}
Conclusion
Becoming adept at factorial calculations in Java is a stepping stone towards understanding and implementing more complex algorithms and data structures. Java provides a plethora of approaches to perform this operation, catering to various programming styles and requirements.