2022-11-07 19:01:00 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2022-11-07 19:24:46 +00:00
|
|
|
"encoding/json"
|
2022-11-07 19:01:00 +00:00
|
|
|
"log"
|
2022-11-07 19:24:46 +00:00
|
|
|
"math/big"
|
2022-11-07 19:01:00 +00:00
|
|
|
"net"
|
|
|
|
|
|
|
|
"protohackers/pkg/conn"
|
|
|
|
)
|
|
|
|
|
2022-11-07 19:24:46 +00:00
|
|
|
var (
|
|
|
|
malformedResponse = []byte("malformed\n")
|
|
|
|
trueResponse = []byte(`{"method":"isPrime","prime":true}` + "\n")
|
|
|
|
falseResponse = []byte(`{"method":"isPrime","prime":false}` + "\n")
|
|
|
|
)
|
|
|
|
|
2022-11-07 19:01:00 +00:00
|
|
|
type data struct {
|
2022-11-07 19:24:46 +00:00
|
|
|
Method string `json:"method"`
|
|
|
|
Number *float64 `json:"number"`
|
2022-11-07 19:01:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2023-09-15 21:20:51 +00:00
|
|
|
err := conn.StartSimpleTCP(primetime)
|
2022-11-07 19:01:00 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatalln(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func primetime(c net.Conn) {
|
2022-11-07 23:02:36 +00:00
|
|
|
if err := conn.ReadAndRespond(c, process); err != nil {
|
2022-11-07 19:24:46 +00:00
|
|
|
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
|
2022-11-07 19:01:00 +00:00
|
|
|
}
|