-
-
Save ydzhou/07b22fc641046ff59585b326a582104e to your computer and use it in GitHub Desktop.
Get all the primes within N
This file contains 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" | |
"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