5] The factorial function n! has value 1when n<=1 and value n *(n-1)! When n is >1. Write both a recursive and iterative algorithm to compute n!.
Recursive Algorithm:
public class FactorialRecursive {
public static int factorial(int n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
int n = 5; // Change the value of n as needed
int result = factorial(n);
System.out.println("Factorial of " + n + " is " + result);
}
}
### output:-
Factorial of 5 is 120
Iterative Algorithm:
public class FactorialIterative {
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int n = 5; // Change the value of n as needed
int result = factorial(n);
System.out.println("Factorial of " + n + " is " + result);
}
}
### ouput:-
Factorial of 5 is 120