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.

Revisions

  1. Bobochka created this gist Sep 23, 2017.
    40 changes: 40 additions & 0 deletions eratosphene.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    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
    }