feat: add GCD and LCM function

This commit is contained in:
dudaodong
2023-05-06 11:02:00 +08:00
parent 945c59896b
commit 654ba15aaf
2 changed files with 80 additions and 0 deletions

View File

@@ -256,3 +256,45 @@ func IsPrime(n int) bool {
return true
}
// GCD return greatest common divisor (GCD) of integers.
// Play: todo
func GCD[T constraints.Integer](integers ...T) T {
result := integers[0]
for k := range integers {
result = gcd(integers[k], result)
if result == 1 {
return 1
}
}
return result
}
// find greatest common divisor (GCD)
func gcd[T constraints.Integer](a, b T) T {
if b == 0 {
return a
}
return gcd(b, a%b)
}
// LCM return Least Common Multiple (LCM) of integers.
// Play: todo
func LCM[T constraints.Integer](integers ...T) T {
result := integers[0]
for i := 1; i < len(integers)-1; i++ {
result = lcm(result, integers[i])
}
return result
}
// find Least Common Multiple (LCM) via GCD.
func lcm[T constraints.Integer](a, b T) T {
return a * b / gcd(a, b)
}