Input: 5
Output: 120
package jan27;
public class Factorial {
public static void main(String[] args) {
int n = 5;
System.out.println(factorial(n)); // Output: 120 (5 * 4 * 3 * 2 * 1)
}
/**
* Calculates factorial of n using recursion.
*
* Time Complexity: O(n)
* - One recursive call per decrement from n to 0
*
* Space Complexity: O(n)
* - Due to call stack depth in recursion from n down to 0
*/
private static int factorial(int n) {
if (n == 0) return 1; // BASE CASE
int temp = factorial(n - 1); // FAITH
return n * temp; // WORK
}
}
📊 Summary Table:
Case Time Complexity Space Complexity Explanation All Cases O(n) O(n) Recurses once per level; no loops or extra memory used
No comments:
Post a Comment