/
cmd.go
75 lines (56 loc) · 1.37 KB
/
cmd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//+build !test
package main
import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"time"
"github.com/cheggaaa/pb"
)
func main() {
limit := flag.Uint64("l", 100000, "Upper limit for prime searching")
write := flag.Bool("s", false, "Save the prime numbers to primes.txt")
flag.Usage = func() {
fmt.Fprintln(os.Stderr, "A quick test implementing the Sieve of Eratostenes in Go")
fmt.Fprintln(os.Stderr, "It searches for prime numbers up to the specified limit")
fmt.Fprintf(os.Stderr, "Usage: %s [-l limit] [-s]\n\n", filepath.Base(os.Args[0]))
flag.PrintDefaults()
fmt.Fprint(os.Stderr, "\n")
}
flag.Parse()
primes := allocate(*limit)
fmt.Printf("Finding all primes <= %v\n", *limit)
start := time.Now()
sieve(*limit, primes)
fmt.Printf("Done in %v.\n", time.Since(start))
if *write {
file, err := os.Create("primes.txt")
if err != nil {
panic(err)
}
defer file.Close()
fmt.Printf("\nSaving them to primes.txt\n")
start := time.Now()
if *limit >= 2 {
fmt.Fprintln(file, 2)
}
output(file, primes)
fmt.Printf("Done in %v.\n", time.Since(start))
}
}
func output(w io.Writer, primes []uint64) {
bar := pb.StartNew(len(primes))
bar.SetMaxWidth(80)
bar.ShowCounters = false
for k, p := range primes {
bar.Increment()
for l := uint8(0); l < 64; l++ {
if (p>>l)&1 == 0 {
fmt.Fprintln(w, (k*64+int(l))*2+3)
}
}
}
bar.Finish()
}