Skip to content

Instantly share code, notes, and snippets.

@ydzhou
Created January 12, 2021 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ydzhou/07b22fc641046ff59585b326a582104e to your computer and use it in GitHub Desktop.
Save ydzhou/07b22fc641046ff59585b326a582104e to your computer and use it in GitHub Desktop.
Get all the primes within N
package main
import (
"fmt"
"math"
"sync"
)
var wg sync.WaitGroup
func isPrime(num int, primes chan<- int) {
defer wg.Done()
maxFactor := int(math.Sqrt(float64(num)))
for i := 2; i <= maxFactor; i ++ {
if num % i == 0 {
return
}
}
primes <- num
}
func main() {
N := 100000
primes := make(chan int, maxNum)
for i := 1; i < N; i ++ {
wg.Add(1)
go isPrime(i, primes)
}
wg.Wait()
close(primes)
for p := range primes {
fmt.Println(p)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment