Last active
May 24, 2022 19:32
-
-
Save caelifer/f12b3a11aa2e151894b58dcc25237c08 to your computer and use it in GitHub Desktop.
Revisions
-
caelifer revised this gist
May 24, 2022 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,4 @@ // Live code - https://go.dev/play/p/EqW-c0gbRqr package main -
caelifer revised this gist
May 24, 2022 . 1 changed file with 0 additions and 2 deletions.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,7 +1,5 @@ // Live code - https://go.dev/play/p/h2roawBCKH_W package main import ( -
caelifer created this gist
May 24, 2022 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,55 @@ // Live code - https://go.dev/play/p/h2roawBCKH_W // You can edit this code! // Click here and start typing. 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 }