package main import ( "bufio" "encoding/json" "log" "math/big" "net" "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 { Method string `json:"method"` Number *float64 `json:"number"` } func main() { err := conn.StartSimple(primetime) if err != nil { log.Fatalln(err) } } func primetime(c net.Conn) { 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 }