-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
96 lines (87 loc) · 1.34 KB
/
utils.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package aoc2023
import (
"strconv"
)
type addable interface {
~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~int64 | ~uint64 | ~int | ~uint
}
func SumSlice[S ~[]V, V addable](s S) (sum V) {
for _, v := range s {
sum += v
}
return sum
}
func SumMapVal[M ~map[K]V, K comparable, V addable](m M) (sum V) {
for _, v := range m {
sum += v
}
return sum
}
func ProdMapVal[M ~map[K]V, K comparable, V addable](m M) (prod V) {
prod = 1
for _, v := range m {
prod *= v
}
return prod
}
func Atoi(s string) int {
i, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return i
}
func IntFieldsIter(s string, fn func(i int)) {
i := 0
for {
for ; i < len(s) && s[i] == ' '; i++ {
}
beg := i
var v int
for ; i < len(s) && s[i] != ' '; i++ {
v = v*10 + int(s[i]-'0')
}
if beg == i {
return
}
fn(v)
}
}
// https://en.wikipedia.org/wiki/Greatest_common_divisor#Binary_GCD_algorithm
func GCD(a, b int) int {
d := 0
for {
if a == b {
return a << d
}
if a%2 == 0 && b%2 == 0 {
a /= 2
b /= 2
d++
continue
}
if a%2 == 0 {
a /= 2
continue
}
if b%2 == 0 {
b /= 2
continue
}
if a < b {
a, b = b, a
}
a = (a - b) / 2
}
}
func GCM(vs []int) int {
if len(vs) == 0 {
return 1
}
gcm := vs[0]
for _, v := range vs[1:] {
d := GCD(gcm, v)
gcm = gcm / d * v
}
return gcm
}