Skip to content

Instantly share code, notes, and snippets.

@elbow-jason
Created November 11, 2015 17:18
Show Gist options
  • Save elbow-jason/16fcfd61ecb8afbdf0c3 to your computer and use it in GitHub Desktop.
Save elbow-jason/16fcfd61ecb8afbdf0c3 to your computer and use it in GitHub Desktop.
fibber
package main
import (
"math/big"
"os"
"strconv"
)
func Fib(n int) *big.Int {
switch n {
case 0:
return big.NewInt(0)
case 1:
return big.NewInt(1)
default:
return calcFib(n)
}
}
func calcFib(n int) *big.Int {
zero := big.NewInt(0)
prevHolder := big.NewInt(0)
onePrev := big.NewInt(1)
twoPrev := big.NewInt(0)
accumulator := 3
for accumulator <= n {
prevHolder = prevHolder.Add(onePrev, zero)
onePrev = onePrev.Add(onePrev, twoPrev)
twoPrev = twoPrev.Add(prevHolder, zero)
accumulator = accumulator + 1
}
return onePrev.Add(onePrev, twoPrev)
}
func main() {
if len(os.Args) < 2 {
println("fibber expects a positive integer as the second arg")
}
n, err := strconv.Atoi(os.Args[1])
if err != nil || n < 0 {
println("Invalid argument for fibber. Expected a positive integer as the second arg.")
os.Exit(1)
}
println(Fib(n).String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment