factor.gno
1.84 Kb · 79 lines
1// Package factor is a Gauntlet judge: factor a number into primes.
2//
3// Answers look like "2*2*3*7" (ascending, separated by "*"). Checking an
4// answer is cheap: multiply the factors back and test each one for
5// primality. Finding them is the work.
6package factor
7
8import (
9 "strconv"
10 "strings"
11
12 "gno.land/r/g188c5k6v0tmfyevfzj962jkajjqt4ddtml8zw0x/gauntlet"
13)
14
15const max = 10_000_000
16
17func init(cur realm) {
18 gauntlet.RegisterJudge(cross(cur), "Prime factors",
19 "Factor n (2 <= n < 10,000,000) as ascending primes joined by *, e.g. 84 -> 2*2*3*7. 6 random n.", Inputs, Check)
20}
21
22// Inputs returns 6 random numbers for a seed.
23func Inputs(seed uint64) []string {
24 r := rng{seed}
25 out := make([]string, 0, 6)
26 for i := 0; i < 6; i++ {
27 n := 2 + r.next()%(max-2)
28 out = append(out, strconv.FormatUint(n, 10))
29 }
30 return out
31}
32
33// Check reports whether out is the ascending prime factorization of in.
34func Check(in, out string) bool {
35 n, err := strconv.ParseUint(in, 10, 64)
36 if err != nil || n < 2 {
37 return false
38 }
39 prod := uint64(1)
40 prev := uint64(0)
41 for _, f := range strings.Split(out, "*") {
42 p, err := strconv.ParseUint(strings.TrimSpace(f), 10, 64)
43 if err != nil || p < prev || !isPrime(p) {
44 return false
45 }
46 prev = p
47 prod *= p
48 if prod > n {
49 return false
50 }
51 }
52 return prod == n
53}
54
55func isPrime(p uint64) bool {
56 if p < 2 {
57 return false
58 }
59 for d := uint64(2); d*d <= p; d++ {
60 if p%d == 0 {
61 return false
62 }
63 }
64 return true
65}
66
67type rng struct{ s uint64 }
68
69func (r *rng) next() uint64 {
70 r.s += 0x9e3779b97f4a7c15
71 z := r.s
72 z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
73 z = (z ^ (z >> 27)) * 0x94d049bb133111eb
74 return z ^ (z >> 31)
75}
76
77func Render(_ string) string {
78 return "# Prime factors judge\n\nA [Gauntlet](/r/g188c5k6v0tmfyevfzj962jkajjqt4ddtml8zw0x/gauntlet:judges) judge. Read the source to see exactly how answers are checked.\n"
79}