-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
79 lines (66 loc) · 1.31 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"bufio"
"encoding/json"
"github.com/bbeck/protohackers/internal"
"io"
"math"
"net"
)
type Request struct {
Method *string `json:"method"`
Number *float64 `json:"number"`
}
const Prime = `{"method":"isPrime","prime":true}` + "\n"
const NotPrime = `{"method":"isPrime","prime":false}` + "\n"
const Malformed = `{"method":"malformed"}` + "\n"
func main() {
internal.RunTCPServer(func(conn net.Conn) {
defer conn.Close()
r := bufio.NewReaderSize(conn, 1024*1024)
for {
bs, _, err := r.ReadLine()
if err != nil {
io.WriteString(conn, Malformed)
return
}
var request Request
if err := json.Unmarshal(bs, &request); err != nil || IsMalformed(request) {
io.WriteString(conn, Malformed)
return
}
if IsPrime(*request.Number) {
io.WriteString(conn, Prime)
} else {
io.WriteString(conn, NotPrime)
}
}
})
}
func IsMalformed(r Request) bool {
if r.Method == nil || *r.Method != "isPrime" || r.Number == nil {
return true
}
if r.Number == nil {
return true
}
return false
}
func IsPrime(n float64) bool {
if _, frac := math.Modf(n); frac != 0. {
return false
}
if n <= 1. {
return false
}
if n <= 3. {
return true
}
sqrt := math.Sqrt(n)
for i := 2.; i <= sqrt; i++ {
if math.Mod(n, i) == 0. {
return false
}
}
return true
}