forked from ociule/codeeval
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfibonacci.go
More file actions
45 lines (41 loc) · 727 Bytes
/
fibonacci.go
File metadata and controls
45 lines (41 loc) · 727 Bytes
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
package main
import "fmt"
import "log"
import "bufio"
import "os"
import "strings"
func fib(n uint, cache []uint) uint {
// This is the same as fibonacci(n), actually
// We should do it in closed form
if n == 0 {
return 0
}
if n == 1 {
return 1
}
if n == 2 {
return 1
}
if cache[n] > 0 {
return cache[n]
} else {
fibN := fib(n-2, cache) + fib(n-1, cache)
cache[n] = fibN
return fibN
}
}
func main() {
file, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
cache := make([]uint, 1000)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
var n uint
fmt.Sscanf(line, "%d", &n)
fmt.Println(fib(n, cache))
}
}