Last active
May 24, 2022 19:32
-
-
Save caelifer/f12b3a11aa2e151894b58dcc25237c08 to your computer and use it in GitHub Desktop.
Fibonacci number calculator implemented using Go generics.
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
// 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: