1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add IsPrime

This commit is contained in:
dudaodong
2023-03-30 11:54:20 +08:00
parent 91503b1656
commit 027abd6ad5
3 changed files with 45 additions and 0 deletions

View File

@@ -240,3 +240,19 @@ func PointDistance(x1, y1, x2, y2 float64) float64 {
return math.Sqrt(c)
}
// IsPrimes checks if number is prime number.
// Play: todo
func IsPrime(n int) bool {
if n < 2 {
return false
}
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
if n%i == 0 {
return false
}
}
return true
}

View File

@@ -263,3 +263,21 @@ func ExamplePointDistance() {
// Output:
// 5
}
func ExampleIsPrime() {
result1 := IsPrime(-1)
result2 := IsPrime(0)
result3 := IsPrime(1)
result4 := IsPrime(2)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// false
// false
// false
// true
}

View File

@@ -200,3 +200,14 @@ func TestPointDistance(t *testing.T) {
assert.Equal(float64(5), result1)
}
func TestIsPrime(t *testing.T) {
assert := internal.NewAssert(t, "TestIsPrime")
assert.Equal(false, IsPrime(-1))
assert.Equal(false, IsPrime(0))
assert.Equal(false, IsPrime(1))
assert.Equal(true, IsPrime(2))
assert.Equal(true, IsPrime(3))
assert.Equal(false, IsPrime(4))
}