101 Logo
onenoughtone

Code Implementation

Factorial Calculator Implementation

Below is the implementation of the factorial calculator:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Recursive approach
function factorialRecursive(n) {
// Base case: 0! = 1! = 1
if (n === 0 || n === 1) {
return 1;
}
// Recursive case: n! = n * (n-1)!
return n * factorialRecursive(n - 1);
}
// Iterative approach
function factorialIterative(n) {
// Handle base case
if (n === 0 || n === 1) {
return 1;
}
let result = 1;
// Multiply from 1 to n
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// Tail-recursive approach
function factorialTailRecursive(n, accumulator = 1) {
// Base case
if (n === 0 || n === 1) {
return accumulator;
}
// Tail-recursive call
return factorialTailRecursive(n - 1, n * accumulator);
}
// Test cases
console.log(factorialRecursive(5)); // 120
console.log(factorialIterative(5)); // 120
console.log(factorialTailRecursive(5)); // 120
console.log(factorialRecursive(0)); // 1
console.log(factorialIterative(0)); // 1
console.log(factorialTailRecursive(0)); // 1
console.log(factorialRecursive(10)); // 3628800
console.log(factorialIterative(10)); // 3628800
console.log(factorialTailRecursive(10)); // 3628800

Step-by-Step Explanation

Let's break down the implementation:

  1. Understand the Problem: The factorial of n (n!) is the product of all positive integers less than or equal to n. By definition, 0! = 1.
  2. Identify Base Cases: For factorial, the base cases are 0! = 1 and 1! = 1. These are the stopping conditions for our recursion.
  3. Define the Recursive Relation: The recursive relation for factorial is n! = n × (n-1)!. This forms the core of our recursive solution.
  4. Implement the Recursive Solution: Write a function that handles the base cases and implements the recursive relation for other inputs.
  5. Consider Alternative Approaches: Implement iterative and tail-recursive solutions to compare efficiency and avoid potential stack overflow.
ProblemSolutionCode
101 Logo
onenoughtone