-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfibonacci.go
59 lines (48 loc) · 1.29 KB
/
fibonacci.go
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
package fibonacci
// lookupTable stores computed results from FibonacciFast or FibonacciFastest.
var lookupTable = map[uint64]uint64{}
// Fibonacci computes the Fibonacci number for n.
func Fibonacci(n uint64) uint64 {
if n == 0 {
return 0
} else if n == 1 {
return 1
}
return Fibonacci(n-1) + Fibonacci(n-2)
}
// FibonacciFast is similar to Fibonacci, with the only difference that computed
// results are stored in a lookup table. This makes FibonacciFast several
// million times faster than Fibonacci.
func FibonacciFast(n uint64) uint64 {
if _, resultExists := lookupTable[n]; resultExists {
return lookupTable[n]
}
var result uint64
if n == 0 {
result = 0
} else if n == 1 {
result = 1
} else {
result = FibonacciFast(n-1) + FibonacciFast(n-2)
}
lookupTable[n] = result
return result
}
// FibonacciFastest is similar to FibonacciFast, with the only difference that
// the lookup table is accessed only once. This makes FibonacciFastest twice as
// fast as FibonacciFast.
func FibonacciFastest(n uint64) uint64 {
if result, resultExists := lookupTable[n]; resultExists {
return result
}
var result uint64
if n == 0 {
result = 0
} else if n == 1 {
result = 1
} else {
result = FibonacciFastest(n-1) + FibonacciFastest(n-2)
}
lookupTable[n] = result
return result
}