Skip to content

Instantly share code, notes, and snippets.

@Bobochka
Created September 23, 2017 11:58
Show Gist options
  • Select an option

  • Save Bobochka/b6d145c35d45edb76359a78d47d9c789 to your computer and use it in GitHub Desktop.

Select an option

Save Bobochka/b6d145c35d45edb76359a78d47d9c789 to your computer and use it in GitHub Desktop.
Eratosphenes sieve
package main
import (
"fmt"
"reflect"
)
func main() {
resGot := primesUpTo(30)
resWant := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}
if !reflect.DeepEqual(resGot, resWant) {
fmt.Println("Wrong result:", resGot)
}
}
func primesUpTo(n int) []int {
primes := make([]bool, n+1)
for i := 2; i <= n; i++ {
primes[i] = true
}
for i := 2; i*i <= n; i++ {
if primes[i] {
for j := 2 * i; j <= n; j += i {
primes[j] = false
}
}
}
res := []int{}
for i, isPrime := range primes {
if isPrime {
res = append(res, i)
}
}
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment