eratosthenes_parallel/eratosthenes_parallel.go

53 lines
881 B
Go
Raw Normal View History

package main
import (
"fmt"
"os"
2021-07-13 00:13:44 +02:00
"runtime"
"strconv"
2021-07-13 00:13:44 +02:00
"sync"
"time"
)
2021-07-13 00:13:44 +02:00
var markGroup sync.WaitGroup
func markMultiples(sieve []uint64, i int64, n0, n1 int64) {
for j := n0; j < n1; j += 2 * i {
sieve[j>>7] |= 1 << ((j & 0x7F) >> 1)
}
markGroup.Done()
}
func main() {
n, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil {
panic(err)
}
2021-07-13 00:13:44 +02:00
nCpus := int64(runtime.NumCPU())
t0 := time.Now()
2021-07-12 21:09:22 +02:00
sieve := make([]uint64, (n>>7)+1)
var found int64
var i int64
i = 2
found++
for i = 3; i < n; i += 2 {
2021-07-12 21:09:22 +02:00
if (sieve[i>>7] & (1 << ((i & 0x7F) >> 1))) == 0 {
found++
2021-07-13 00:13:44 +02:00
p := nCpus
var jnext int64
for j := i * i; j < n; j = jnext {
jnext = ((n-j)/(2*i)/p+1)*(2*i) + j
markGroup.Add(1)
go markMultiples(sieve, i, j, jnext)
p--
}
2021-07-13 00:13:44 +02:00
markGroup.Wait()
}
}
d := time.Since(t0)
fmt.Println()
fmt.Println(found, "primes found in", d)
}