-
Notifications
You must be signed in to change notification settings - Fork 0
/
fib.js
70 lines (62 loc) · 1.04 KB
/
fib.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function fibSlow(n)
{
if (n < 0)
return 0
if (n <= 1)
return n
return fibSlow(n - 1) + fibSlow(n - 2)
}
function fibMemo(n, cache = {})
{
if (n < 0)
return 0
if (n <= 1)
return n
if (!cache[n])
cache[n] = fibMemo(n - 1, cache) + fibMemo(n - 2, cache)
return cache[n]
}
function fibDynamicProgramming(n)
{
if (n <= 0)
return 0
let [prev, cur] = [0, 1]
while (--n > 0)
[prev, cur] = [cur, prev + cur]
return cur
}
function* generatorDP()
{
yield 0;
let [prev, cur] = [0, 1]
while (true)
{
[prev, cur] = [cur, prev + cur]
yield cur
}
}
function fibGenerator(n)
{
if (n < 0)
return 0
let i;
for (i of generatorDP())
{
n--;
if (n == 0)
break
}
return i;
}
console.time('fibSlow')
console.log(fibSlow(11))
console.timeEnd('fibSlow')
console.time('fibMemo')
console.log(fibMemo(11))
console.timeEnd('fibMemo')
console.time('fibDynamicProgramming')
console.log(fibDynamicProgramming(11))
console.timeEnd('fibDynamicProgramming')
console.time('fibGenerator')
console.log(fibGenerator(11))
console.timeEnd('fibGenerator')