I've implemented two Java codes for calculating the factorial of a number, one using recursion and the other using iteration. The iterative code seems to be faster than the recursive code in terms of execution time. However, I'm curious to understand why this performance difference occurs.
Recursive Factorial Code:
public class RecursiveFactorial {
public static long factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
int number = 5;
long startTime = System.nanoTime();
long result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
long endTime = System.nanoTime();
double executionTime = (endTime - startTime) / 1_000_000_000.0;
System.out.println("Execution time: " + executionTime + " seconds");
}
}
time: 0.0138802 seconds
Iterative Factorial Code:
public class IterativeFactorial {
public static long factorial(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int number = 5;
long startTime = System.nanoTime();
long result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
long endTime = System.nanoTime();
double executionTime = (endTime - startTime) / 1_000_000_000.0;
System.out.println("Execution time: " + executionTime + " seconds");
}
}
time: 0.0003859 seconds
I would appreciate if someone could shed light on the reasons behind the observed performance difference between the recursive and iterative implementations. Additionally, it would be interesting to see some random execution times for both codes to further illustrate the disparity.