Last active
July 28, 2023 18:29
-
-
Save jreisinger/92919dabc0905a1cd22d5288b4a6e4ec to your computer and use it in GitHub Desktop.
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 characters
// Fibsrv is an HTTP server that calculate Fibonacci numbers. | |
package main | |
import ( | |
"fmt" | |
"log" | |
"math/big" | |
"net/http" | |
"strconv" | |
) | |
func main() { | |
http.HandleFunc("/", fibHandle) | |
log.Fatal(http.ListenAndServe("localhost:8000", nil)) | |
} | |
func fibHandle(w http.ResponseWriter, r *http.Request) { | |
s := r.URL.Query().Get("fib") | |
// s := strings.Split(r.URL.Path, "/")[1] | |
n, err := strconv.ParseUint(s, 10, 64) | |
if err != nil { | |
w.WriteHeader(http.StatusBadRequest) | |
fmt.Fprintf(w, "%q is not unsigned int", s) | |
return | |
} | |
if n > 999999 { | |
fmt.Fprint(w, "Whoa, who am I, a millionare?\n") | |
return | |
} | |
res := fib(uint(n)) | |
fmt.Fprintf(w, "%d\n", res) | |
} | |
// fib calculates nth number from the Fibonacci sequence. | |
func fib(n uint) *big.Int { | |
if n < 2 { | |
return big.NewInt(int64(n)) | |
} | |
a, b := big.NewInt(0), big.NewInt(1) | |
for n--; n > 0; n-- { | |
a.Add(a, b) | |
a, b = b, a | |
} | |
return b | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment