Skip to content

Commit 321ca3d

Browse files
committed
feat(js): add solution and documentation for easy challenge 4 - Factorial calculator
1 parent 287d6d4 commit 321ca3d

File tree

2 files changed

+128
-0
lines changed

2 files changed

+128
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Develop a recursive or iterative function to calculate the factorial of a non-negative integer. Consider handling special cases such as negative numbers.
7+
8+
### Code Explanation
9+
The code presents two functions to calculate the factorial:
10+
11+
- `factorialRecursive(n)`: Calculates the factorial recursively. If `n` is negative, it throws an error. If `n` is 0 or 1, it returns 1. Otherwise, it returns `n` multiplied by the factorial of `n-1`.
12+
13+
- `factorialIterative(n)`: Calculates the factorial iteratively. If `n` is negative, it throws an error. It initializes `result` to 1 and successively multiplies by each number from 2 to `n`.
14+
15+
### Relevant Code Snippet
16+
17+
```javascript
18+
function factorialRecursive(n) {
19+
if (n < 0) {
20+
throw new Error("Factorial is not defined for negative numbers");
21+
}
22+
if (n === 0 || n === 1) {
23+
return 1;
24+
}
25+
return n * factorialRecursive(n - 1);
26+
}
27+
28+
function factorialIterative(n) {
29+
if (n < 0) {
30+
throw new Error("Factorial is not defined for negative numbers");
31+
}
32+
let result = 1;
33+
for (let i = 2; i <= n; i++) {
34+
result *= i;
35+
}
36+
return result;
37+
}
38+
```
39+
40+
### Example Usage
41+
42+
```javascript
43+
const testValues = [0, 1, 5, 7];
44+
testValues.forEach(val => {
45+
console.log(`Factorial of ${val} (recursive): ${factorialRecursive(val)}`);
46+
console.log(`Factorial of ${val} (iterative): ${factorialIterative(val)}`);
47+
});
48+
```
49+
50+
---
51+
52+
## Versión en Español
53+
54+
### Descripción del Reto
55+
Desarrolla una función recursiva o iterativa para calcular el factorial de un número entero no negativo. Considera el manejo de casos especiales como números negativos.
56+
57+
### Explicación del Código
58+
El código presenta dos funciones para calcular el factorial:
59+
60+
- `factorialRecursive(n)`: Calcula el factorial de forma recursiva. Si `n` es negativo, lanza un error. Si `n` es 0 o 1, retorna 1. En otro caso, retorna `n` multiplicado por el factorial de `n-1`.
61+
62+
- `factorialIterative(n)`: Calcula el factorial de forma iterativa. Si `n` es negativo, lanza un error. Inicializa `result` en 1 y multiplica sucesivamente por cada número desde 2 hasta `n`.
63+
64+
### Fragmento de Código Relevante
65+
66+
```javascript
67+
function factorialRecursive(n) {
68+
if (n < 0) {
69+
throw new Error("Factorial is not defined for negative numbers");
70+
}
71+
if (n === 0 || n === 1) {
72+
return 1;
73+
}
74+
return n * factorialRecursive(n - 1);
75+
}
76+
77+
function factorialIterative(n) {
78+
if (n < 0) {
79+
throw new Error("Factorial is not defined for negative numbers");
80+
}
81+
let result = 1;
82+
for (let i = 2; i <= n; i++) {
83+
result *= i;
84+
}
85+
return result;
86+
}
87+
```
88+
89+
### Ejemplo de Uso
90+
91+
```javascript
92+
const testValues = [0, 1, 5, 7];
93+
testValues.forEach(val => {
94+
console.log(`Factorial de ${val} (recursivo): ${factorialRecursive(val)}`);
95+
console.log(`Factorial de ${val} (iterativo): ${factorialIterative(val)}`);
96+
});
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Challenge: Develop a recursive or iterative function to calculate the factorial of a non-negative integer.
2+
// Consider handling special cases such as negative numbers.
3+
4+
// Recursive factorial function
5+
function factorialRecursive(n) {
6+
if (n < 0) {
7+
throw new Error("Factorial is not defined for negative numbers");
8+
}
9+
if (n === 0 || n === 1) {
10+
return 1;
11+
}
12+
return n * factorialRecursive(n - 1);
13+
}
14+
15+
// Iterative factorial function
16+
function factorialIterative(n) {
17+
if (n < 0) {
18+
throw new Error("Factorial is not defined for negative numbers");
19+
}
20+
let result = 1;
21+
for (let i = 2; i <= n; i++) {
22+
result *= i;
23+
}
24+
return result;
25+
}
26+
27+
// Example usage
28+
const testValues = [0, 1, 5, 7];
29+
testValues.forEach(val => {
30+
console.log(`Factorial of ${val} (recursive): ${factorialRecursive(val)}`);
31+
console.log(`Factorial of ${val} (iterative): ${factorialIterative(val)}`);
32+
});

0 commit comments

Comments
 (0)