Compute and print primes (non-parallel)
This is already a slightly optimized version: I hardcode 2 and compute only odd primes and I skip multiples of lesser primes in the inner loop. This roughly matches the algorithm used by Dave Plummer in his Youtube series. Just to have the same baseline
This commit is contained in:
commit
27b131c982
|
@ -0,0 +1,44 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
n, err := strconv.ParseInt(os.Args[1], 10, 64)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
t0 := time.Now()
|
||||
sieve := make([]bool, n)
|
||||
col := 0
|
||||
var found int64
|
||||
var i int64
|
||||
i = 2
|
||||
found++
|
||||
s := fmt.Sprintf("%d, ", i)
|
||||
fmt.Print(s)
|
||||
col += len(s)
|
||||
for i = 3; i < n; i += 2 {
|
||||
if !sieve[i] {
|
||||
found++
|
||||
s := fmt.Sprintf("%d, ", i)
|
||||
if col+len(s) > 80 {
|
||||
fmt.Print("\n")
|
||||
col = 0
|
||||
}
|
||||
fmt.Print(s)
|
||||
col += len(s)
|
||||
for j := i * i; j < n; j += 2 * i {
|
||||
sieve[j] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
d := time.Since(t0)
|
||||
fmt.Println()
|
||||
fmt.Println(found, "primes found in", d)
|
||||
|
||||
}
|
Loading…
Reference in New Issue