2021-07-12 19:40:34 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2021-07-13 00:13:44 +02:00
|
|
|
"runtime"
|
2021-07-12 19:40:34 +02:00
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2021-07-13 12:09:17 +02:00
|
|
|
type work struct {
|
|
|
|
i int64
|
|
|
|
n0, n1 int64
|
|
|
|
}
|
|
|
|
|
|
|
|
type result bool
|
2021-07-13 00:13:44 +02:00
|
|
|
|
2021-07-13 12:09:17 +02:00
|
|
|
func markMultiples(sieve []uint64, workCh chan work, resultCh chan result) {
|
|
|
|
for {
|
|
|
|
w := <-workCh
|
|
|
|
for j := w.n0; j < w.n1; j += 2 * w.i {
|
|
|
|
sieve[j>>7] |= 1 << ((j & 0x7F) >> 1)
|
|
|
|
}
|
|
|
|
resultCh <- true
|
2021-07-13 00:13:44 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-12 19:40:34 +02:00
|
|
|
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())
|
2021-07-12 19:40:34 +02:00
|
|
|
t0 := time.Now()
|
2021-07-12 21:09:22 +02:00
|
|
|
sieve := make([]uint64, (n>>7)+1)
|
2021-07-13 12:09:17 +02:00
|
|
|
workCh := make(chan work)
|
|
|
|
resultCh := make(chan result)
|
2021-07-12 19:40:34 +02:00
|
|
|
var i int64
|
2021-07-13 12:09:17 +02:00
|
|
|
for i = 0; i < nCpus; i++ {
|
|
|
|
go markMultiples(sieve, workCh, resultCh)
|
|
|
|
}
|
|
|
|
var found int64
|
2021-07-12 19:40:34 +02:00
|
|
|
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 {
|
2021-07-12 19:40:34 +02:00
|
|
|
found++
|
2021-07-13 00:13:44 +02:00
|
|
|
|
|
|
|
p := nCpus
|
|
|
|
var jnext int64
|
2021-07-13 11:17:37 +02:00
|
|
|
// XXX - i * i can overflow.
|
|
|
|
// bail out before that happens
|
|
|
|
if n / i < i {
|
|
|
|
continue;
|
|
|
|
}
|
2021-07-13 12:09:17 +02:00
|
|
|
workers := 0
|
2021-07-13 00:13:44 +02:00
|
|
|
for j := i * i; j < n; j = jnext {
|
|
|
|
jnext = ((n-j)/(2*i)/p+1)*(2*i) + j
|
2021-07-13 11:17:37 +02:00
|
|
|
if jnext > n {
|
|
|
|
jnext = n
|
|
|
|
}
|
2021-07-13 12:09:17 +02:00
|
|
|
workCh <-work{ i, j, jnext }
|
|
|
|
workers++
|
2021-07-13 00:13:44 +02:00
|
|
|
p--
|
2021-07-12 19:40:34 +02:00
|
|
|
}
|
2021-07-13 12:09:17 +02:00
|
|
|
for k := 0; k < workers; k++ {
|
|
|
|
_ = <-resultCh
|
|
|
|
}
|
2021-07-12 19:40:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
d := time.Since(t0)
|
|
|
|
fmt.Println()
|
|
|
|
fmt.Println(found, "primes found in", d)
|
|
|
|
|
|
|
|
}
|