Skip to content

Instantly share code, notes, and snippets.

@caelifer
Last active May 24, 2022 19:32
Show Gist options
  • Save caelifer/f12b3a11aa2e151894b58dcc25237c08 to your computer and use it in GitHub Desktop.
Save caelifer/f12b3a11aa2e151894b58dcc25237c08 to your computer and use it in GitHub Desktop.
Fibonacci number calculator implemented using Go generics.
// Live code - https://go.dev/play/p/EqW-c0gbRqr
package main
import (
"errors"
"fmt"
)
func main() {
for _, i := range []int{-1, 0, 1, 93, 94} {
n, err := Fib(i)
if err != nil {
Print(i, err)
} else {
Print(i, n)
}
}
}
// Integer a generic type to represent all supported integer values
type Integer interface {
~int | ~int8 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint32 | ~uint64
}
// Print pretty prints result for Fibonacci calculation
func Print[T Integer](n T, v any) {
fmt.Printf("Fib(%d) = %v\n", n, v)
}
// Fib returns the n-th fibonacci number
func Fib[T Integer](_n T) (uint64, error) {
// Sentinel condition
if _n < 0 {
return 0, errors.New("bad input")
}
// Up-cast provided input
n := uint64(_n)
if n <= 1 {
return n, nil
}
var n1, n2 uint64 = 0, 1
for i := uint64(1); i < n; i++ {
n1, n2 = n2, n1+n2
if n2 < n1 {
return 0, errors.New("overflow")
}
}
return n2, nil
}
@caelifer
Copy link
Author

Output:

Fib(-1) = bad input
Fib(0) = 0
Fib(1) = 1
Fib(93) = 12200160415121876738
Fib(94) = overflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment