implement primetime

This commit is contained in:
Evan Burkey 2022-11-07 11:24:46 -08:00
parent 71179f5099
commit 594f175472
1 changed files with 30 additions and 2 deletions

View File

@ -1,15 +1,24 @@
package main package main
import ( import (
"bufio"
"encoding/json"
"log" "log"
"math/big"
"net" "net"
"protohackers/pkg/conn" "protohackers/pkg/conn"
) )
var (
malformedResponse = []byte("malformed\n")
trueResponse = []byte(`{"method":"isPrime","prime":true}` + "\n")
falseResponse = []byte(`{"method":"isPrime","prime":false}` + "\n")
)
type data struct { type data struct {
Method string `json:"method"` Method string `json:"method"`
Number int `json:"number"` Number *float64 `json:"number"`
} }
func main() { func main() {
@ -21,4 +30,23 @@ func main() {
func primetime(c net.Conn) { func primetime(c net.Conn) {
defer c.Close() defer c.Close()
sc := bufio.NewScanner(c)
for sc.Scan() {
response := process(sc.Bytes())
c.Write(response)
}
if err := sc.Err(); err != nil {
log.Fatalln(err)
}
}
func process(buf []byte) []byte {
var in data
err := json.Unmarshal(buf, &in)
if err != nil || in.Method != "isPrime" || in.Number == nil {
return malformedResponse
} else if big.NewInt(int64(*in.Number)).ProbablyPrime(0) {
return trueResponse
}
return falseResponse
} }