1
0
gotour-notes/exercises/03-fibonacci/fibonacci.go
Stephen M. McQuay 0e29275c30 use uint64 and panic on false numbers
- break piont at
2012-08-02 16:58:37 -06:00

50 lines
893 B
Go

package main
import (
"flag"
"fmt"
"os"
"strconv"
)
var usage string = "usage: " + os.Args[0] + " <number of fibs>"
// fibonacci is a function that returns
// a function that returns an int.
// from cpython/Doc/build/html/library/functools.html
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
func fibonacci() func() uint64 {
cur_fib := uint64(0)
nxt_fib := cur_fib
return func() uint64 {
if nxt_fib == 0 {
nxt_fib = 1
return 0
}
tmp := cur_fib
cur_fib = nxt_fib
nxt_fib += tmp
if nxt_fib < cur_fib {
panic("overfull!!")
}
return cur_fib
}
}
func main() {
flag.Parse()
if len(flag.Args()) != 1 {
fmt.Fprintln(os.Stderr, usage)
os.Exit(1)
}
count, err := strconv.Atoi(flag.Arg(0))
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(1)
}
f := fibonacci()
for i := 0; i < count; i++ {
fmt.Println(f())
}
}