Skip to content

Instantly share code, notes, and snippets.

@dougyoung
Last active April 15, 2019 06:22
Show Gist options
  • Save dougyoung/48b95fc6cd2b531333d877c603b7e0e9 to your computer and use it in GitHub Desktop.
Save dougyoung/48b95fc6cd2b531333d877c603b7e0e9 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes in Golang - O(n(log(log(n))))
package main
import "fmt"
func sieve(n uint64) []bool {
primeBits := make([]bool, n-2)
for i := uint64(2); i < n; i++ {
for j := i; (i*j)-2 < n-2; j++ {
primeBits[(i*j)-2] = true
}
}
return primeBits
}
func getPrimes(sieve []bool) []uint64 {
n := uint64(len(sieve))
primes := make([]uint64, 0);
for i := uint64(0); i < n; i++ {
if !sieve[i] {
primes = append(primes, i+2)
}
}
return primes
}
func main() {
var n uint64
for {
_, err := fmt.Scanf("%d", &n)
if err != nil {
panic("Unexpected input encountered")
}
if n == 0 {
break
}
sieve := sieve(n)
primes := getPrimes(sieve)
for i := 0; i < len(primes); i++ {
fmt.Println(primes[i])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment