-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction-recursive.html
100 lines (89 loc) · 2.67 KB
/
function-recursive.html
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Recursive Function</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
padding: 2rem;
}
p {
padding: .5rem 0;
}
div {
width: 100%;
height: 100vh;
background-color: rgb(0, 195, 255);
font-weight: 800;
font-size: 2rem;
font-family: sans-serif;
text-transform: uppercase;
display: flex;
justify-content: center;
align-items: center;
color: #0e0e0e;
}
</style>
</head>
<body>
<script>
/*
## Recursive Function
● Recursive function adalah kemampuan function memanggil function dirinya sendiri
● Kadang memang ada banyak problem, yang lebih mudah diselesaikan menggunakan recursive function, seperti contohnya kasus factorial
*/
// =====Kode : Factorial Loop=====
document.writeln(`<p>=====Factorial dengan Loop=====</p>`);
function factorial(value) {
let result = 1;
for (let i = 1; i <= value; i++) {
result *= i;
}
return result;
}
let factorialValue = factorial(2);
document.writeln(`<p>${factorialValue}</p>`);
// =====Kode : Factorial Recursive=====
document.writeln(`<p>=====Factorial dengan Function Recursive=====</p>`);
function factorialRecursive(value) {
if (value === 1) {
return 1;
} else {
return value * factorialRecursive(value - 1);
}
}
factorialValue = factorialRecursive(20);
/*
Cara kerja Function Recursive
5 * factorialRecursive(5 - 1)
5 * 4 * factorialRecursive(4 - 1)
5 * 4 * 3 * factorialRecursive(3 - 1)
5 * 4 * 3 * 2 * factorialRecursive(2 - 1)
5 * 4 * 3 * 2 * 1
*/
document.writeln(`<p>${factorialValue}</p>`);
function onToTen(value) {
document.writeln(`<p>${value}</p>`);
if (value === 1) {
return 1;
} else {
return value + onToTen(value - 2);
}
}
/*
5 + 5 - 2
5 + 3 - 3 - 2
5 + 3 + 1 - 2
*/
let done = onToTen(5)
document.writeln(`<p>${done}</p>`);
</script>
</body>
</html>