mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add GCD and LCM function
This commit is contained in:
@@ -256,3 +256,45 @@ func IsPrime(n int) bool {
|
|||||||
|
|
||||||
return true
|
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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -210,3 +210,41 @@ func TestIsPrime(t *testing.T) {
|
|||||||
assert.Equal(true, IsPrime(3))
|
assert.Equal(true, IsPrime(3))
|
||||||
assert.Equal(false, IsPrime(4))
|
assert.Equal(false, IsPrime(4))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGCD(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestGCD")
|
||||||
|
|
||||||
|
assert.Equal(1, GCD(1, 1))
|
||||||
|
assert.Equal(1, GCD(1, -1))
|
||||||
|
assert.Equal(-1, GCD(-1, 1))
|
||||||
|
assert.Equal(-1, GCD(-1, -1))
|
||||||
|
|
||||||
|
assert.Equal(1, GCD(1, 0))
|
||||||
|
assert.Equal(1, GCD(0, 1))
|
||||||
|
assert.Equal(-1, GCD(-1, 0))
|
||||||
|
assert.Equal(-1, GCD(0, -1))
|
||||||
|
|
||||||
|
assert.Equal(1, GCD(1, -2))
|
||||||
|
assert.Equal(1, GCD(-2, 1))
|
||||||
|
assert.Equal(-1, GCD(-1, 2))
|
||||||
|
assert.Equal(-1, GCD(2, -1))
|
||||||
|
|
||||||
|
assert.Equal(-1, GCD(-1, -2))
|
||||||
|
assert.Equal(-1, GCD(-2, -1))
|
||||||
|
|
||||||
|
assert.Equal(-9, GCD(-27, -36))
|
||||||
|
assert.Equal(3, GCD(3, 6, 9))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLCM(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestLCM")
|
||||||
|
|
||||||
|
assert.Equal(0, LCM(0))
|
||||||
|
assert.Equal(1, LCM(1))
|
||||||
|
assert.Equal(-1, LCM(-1))
|
||||||
|
assert.Equal(0, LCM(0, -1))
|
||||||
|
assert.Equal(0, LCM(0, 1))
|
||||||
|
assert.Equal(1, LCM(1, 1))
|
||||||
|
assert.Equal(1, LCM(1, 2))
|
||||||
|
assert.Equal(6, LCM(3, 6, 9))
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user