commit 27b131c982f63ebcce301d9ada755fb814dd3e34 Author: Peter J. Holzer Date: Mon Jul 12 19:40:34 2021 +0200 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 diff --git a/eratosthenes_parallel.go b/eratosthenes_parallel.go new file mode 100644 index 0000000..6058388 --- /dev/null +++ b/eratosthenes_parallel.go @@ -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) + +}