Created
October 10, 2010 21:00
-
-
Save dansondergaard/619561 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
import "big" | |
func main() { | |
fmt.Println(fib(50)) | |
fmt.Println(fibrec(big.NewInt(10))) | |
fmt.Println(fibbig(big.NewInt(50))) | |
} | |
// The Good -- makes good use of parallel assignment | |
func magic(n int) uint64 { | |
var a uint64 = 0 | |
var b uint64 = 1 | |
for i := 0; i < n; i++ { | |
a, b = b, b + a | |
} | |
return b | |
} | |
// The Bad | |
func fibrec(n *big.Int) *big.Int { | |
if n.Cmp(big.NewInt(0)) == 0 || n.Cmp(big.NewInt(1)) == 0 { | |
return big.NewInt(1) | |
} else { | |
return big.NewInt(0).Add( | |
fibrec(big.NewInt(0).Sub(n, big.NewInt(1))), | |
fibrec(big.NewInt(0).Sub(n, big.NewInt(2)))) | |
} | |
return big.NewInt(0) | |
} | |
// The Ugly | |
func fibbig(n *big.Int) *big.Int { | |
a := big.NewInt(0) | |
b := big.NewInt(1) | |
c := big.NewInt(0) | |
for i := big.NewInt(0); i.Cmp(n) == -1; i.Add(i, big.NewInt(1)) { | |
c.Set(a) | |
a.Set(b) | |
b.Add(b, c) | |
} | |
return b; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment