Saturday, January 29, 2022

Factorial

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:

CaseTime ComplexitySpace ComplexityExplanation
All CasesO(n)O(n)Recurses once per level; no loops or extra memory used

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...