Skip to content

Commit 6fdad95

Browse files
authored
[Reimplementation] Sieve of eratosthenes (#722)
1 parent 2f8c738 commit 6fdad95

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

math/prime/sieve2.go

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/* sieve2.go - Sieve of Eratosthenes
2+
* Algorithm to generate prime numbers up to a limit
3+
* Author: ddaniel27
4+
*/
5+
package prime
6+
7+
func SieveEratosthenes(limit int) []int {
8+
primes := make([]int, 0)
9+
sieve := make([]int, limit+1) // make a slice of size limit+1
10+
11+
for i := 2; i <= limit; i++ {
12+
if sieve[i] == 0 { // if the number is not marked as composite
13+
primes = append(primes, i) // add it to the list of primes
14+
for j := i * i; j <= limit; j += i { // mark all multiples of i as composite
15+
sieve[j] = 1
16+
}
17+
}
18+
}
19+
20+
return primes
21+
}

math/prime/sieve2_test.go

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package prime_test
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
7+
"github.com/TheAlgorithms/Go/math/prime"
8+
)
9+
10+
func TestSieveEratosthenes(t *testing.T) {
11+
tests := []struct {
12+
name string
13+
limit int
14+
want []int
15+
}{
16+
{
17+
name: "First 10 primes test",
18+
limit: 30,
19+
want: []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29},
20+
},
21+
{
22+
name: "First 20 primes test",
23+
limit: 71,
24+
want: []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71},
25+
},
26+
}
27+
28+
for _, tt := range tests {
29+
t.Run(tt.name, func(t *testing.T) {
30+
got := prime.SieveEratosthenes(tt.limit)
31+
32+
if !reflect.DeepEqual(got, tt.want) {
33+
t.Errorf("SieveEratosthenes() = %v, want %v", got, tt.want)
34+
}
35+
})
36+
}
37+
}
38+
39+
func BenchmarkSieveEratosthenes(b *testing.B) {
40+
for i := 0; i < b.N; i++ {
41+
_ = prime.SieveEratosthenes(10)
42+
}
43+
}

0 commit comments

Comments
 (0)