Last active
December 11, 2015 09:38
-
-
Save vderyagin/4581243 to your computer and use it in GitHub Desktop.
Sieve of Erathosthenes prime numbers finding algorithm implemented in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"strconv" | |
) | |
func Primes(n int) []int { | |
numbers := make([]bool, n+1) | |
for idx := range numbers { | |
numbers[idx] = true | |
} | |
return Sieve(numbers) | |
} | |
func Sieve(s []bool) []int { | |
l := len(s) | |
s[0] = false | |
s[1] = false | |
// Filter out non-primes: | |
for idx := 2; idx*idx < l; idx++ { | |
if s[idx] { | |
for i := 2 * idx; i < l; i += idx { | |
s[i] = false | |
} | |
} | |
} | |
primes := make([]int, 0) | |
// Gather remaining into their own slice: | |
for idx, primep := range s { | |
if primep { | |
primes = append(primes, idx) | |
} | |
} | |
return primes | |
} | |
func main() { | |
var upTo int | |
var err error | |
if len(os.Args) == 1 { | |
upTo = 100 | |
} else { | |
upTo, err = strconv.Atoi(os.Args[1]) | |
} | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("%v\n", Primes(upTo)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"reflect" | |
"testing" | |
) | |
func TestPrimes(t *testing.T) { | |
actual := Primes(23) | |
expected := []int{2, 3, 5, 7, 11, 13, 17, 19, 23} | |
if !reflect.DeepEqual(actual, expected) { | |
t.Errorf("%v != %v", actual, expected) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment