Skip to content

Commit 4dfa69f

Browse files
Andres Francisco Villegas PelaezAndres Francisco Villegas Pelaez
authored andcommitted
Add erathosthenesSieve
Added the implementation of the erathostenes sieve in golang. This implementation can find primes numbers up to 10e7 in a deterministic way
1 parent 8990142 commit 4dfa69f

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

eratosthenesSieve.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
//Only works for primes smaller or equal to 10e7
8+
func sieve(upperBound int64) []int64 {
9+
_sieveSize := upperBound + 10
10+
//Creates set to mark wich numbers are primes and wich are not
11+
//true: not primes, false: primes
12+
//this to favor default initialization of arrays in go
13+
var bs [10000010]bool
14+
//creates a slice to save the primes it finds
15+
primes := make([]int64, 0, 1000)
16+
17+
bs[0] = true
18+
bs[1] = true
19+
//iterate over the numbers set
20+
for i := int64(0); i <= _sieveSize; i++ {
21+
//if find one number that is not marked as a compund number, mark all its multiples
22+
if !bs[i] {
23+
for j := i * i; j <= _sieveSize; j += i {
24+
bs[j] = true
25+
}
26+
//Add the prime you just find to the slice of primes
27+
primes = append(primes, i)
28+
}
29+
}
30+
return primes
31+
}
32+
33+
func main() {
34+
//prints first N primes into console
35+
N := 100
36+
primes := sieve(N)
37+
fmt.Println(primes)
38+
}

0 commit comments

Comments
 (0)