Created
September 23, 2017 11:58
-
-
Save Bobochka/b6d145c35d45edb76359a78d47d9c789 to your computer and use it in GitHub Desktop.
Eratosphenes sieve
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" | |
| "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