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"
|
2021-07-13 00:13:44 +02:00
|
|
|
"sync"
|
2021-07-12 19:40:34 +02:00
|
|
|
"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()
|
|
|
|
}
|
|
|
|
|
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-12 19:40:34 +02:00
|
|
|
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 {
|
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 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 00:13:44 +02:00
|
|
|
markGroup.Add(1)
|
|
|
|
go markMultiples(sieve, i, j, jnext)
|
|
|
|
p--
|
2021-07-12 19:40:34 +02:00
|
|
|
}
|
2021-07-13 00:13:44 +02:00
|
|
|
markGroup.Wait()
|
2021-07-12 19:40:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
d := time.Since(t0)
|
|
|
|
fmt.Println()
|
|
|
|
fmt.Println(found, "primes found in", d)
|
|
|
|
|
|
|
|
}
|