Repository navigation
Expand file tree
/
Copy pathrecursion.js
More file actions
71 lines (55 loc) · 1.31 KB
/
Copy pathrecursion.js
File metadata and controls
71 lines (55 loc) · 1.31 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// to test these problems you can run 'node recursion.js' in your terminal
// Problem 1:
let n = 1;
while (n <= 10) {
console.log('While Loop', n);
n++;
}
// write a recursive - function called countToTen that mimics the while loop above.
// code here
let m = 1;
function countToTen() {
if(m > 10) {
return "Recursion complete";
}
console.log('While Loop', m)
return countToTen(++m);
}
// when you code is ready, un-comment the next line and run the file
console.log(countToTen());
/* ================ Next Problem ================= */
// Problem 2:
const factorial = n => {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
};
console.log(factorial(5));
// write the above function in a recursive way.
// const recursiveFactorial = n => {
// let output = n;
// if (n === 1) {
// return output;
// }
// output *= (n-1);
// recursiveFactorial(output);
// };
function recursiveFactorial(n) {
// let output = num;
// if (num === 2) {
// return output;
// }
// output *= (num-1);
// recursiveFactorial(--num);
if (n < 0) {
return 0;
} else if (n === 0) {
return 1;
} else {
return (n * (recursiveFactorial(n-1)));
}
}
// when your code is ready, un-comment the next line and run the file
console.log(recursiveFactorial(5));