File: primes.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2020-2025 pacman64
   5 
   6 Permission is hereby granted, free of charge, to any person obtaining a copy of
   7 this software and associated documentation files (the “Software”), to deal
   8 in the Software without restriction, including without limitation the rights to
   9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10 of the Software, and to permit persons to whom the Software is furnished to do
  11 so, subject to the following conditions:
  12 
  13 The above copyright notice and this permission notice shall be included in all
  14 copies or substantial portions of the Software.
  15 
  16 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22 SOFTWARE.
  23 */
  24 
  25 /*
  26 Single-file source-code for primes.
  27 
  28 To compile a smaller-sized command-line app, you can use the `go` command as
  29 follows:
  30 
  31 go build -ldflags "-s -w" -trimpath primes.go
  32 */
  33 
  34 package main
  35 
  36 import (
  37     "bufio"
  38     "math"
  39     "os"
  40     "strconv"
  41 )
  42 
  43 // Note: the code is avoiding using the fmt package to save hundreds of
  44 // kilobytes on the resulting executable, which is a noticeable difference.
  45 
  46 const info = `
  47 primes [options...] [count...]
  48 
  49 
  50 Show the first few prime numbers, starting from the lowest and showing one
  51 per line. When not given how many primes to find, the default is 1 million.
  52 
  53 All (optional) leading options start with either single or double-dash:
  54 
  55     -h          show this help message
  56     -help       show this help message
  57 `
  58 
  59 func main() {
  60     howMany := 1_000_000
  61     if len(os.Args) > 1 {
  62         switch os.Args[1] {
  63         case `-h`, `--h`, `-help`, `--help`:
  64             os.Stderr.WriteString(info[1:])
  65             return
  66         }
  67 
  68         n, err := strconv.Atoi(os.Args[1])
  69         if err != nil {
  70             os.Stderr.WriteString("\x1b[31m")
  71             os.Stderr.WriteString(err.Error())
  72             os.Stderr.WriteString("\x1b[0m\n")
  73             os.Exit(1)
  74         }
  75 
  76         if n < 0 {
  77             n = 0
  78         }
  79         howMany = n
  80     }
  81 
  82     primes(howMany)
  83 }
  84 
  85 func primes(left int) {
  86     bw := bufio.NewWriter(os.Stdout)
  87     defer bw.Flush()
  88 
  89     // 24 bytes are always enough for any 64-bit integer
  90     var buf [24]byte
  91 
  92     // 2 is the only even prime number
  93     if left > 0 {
  94         bw.WriteString("2\n")
  95         left--
  96     }
  97 
  98     for n := uint64(3); left > 0; n += 2 {
  99         if oddPrime(n) {
 100             bw.Write(strconv.AppendUint(buf[:0], n, 10))
 101             if err := bw.WriteByte('\n'); err != nil {
 102                 // assume errors come from closed stdout pipes
 103                 return
 104             }
 105             left--
 106         }
 107     }
 108 }
 109 
 110 // oddPrime assumes the number given to it is odd
 111 func oddPrime(n uint64) bool {
 112     max := uint64(math.Sqrt(float64(n)))
 113     for div := uint64(3); div <= max; div += 2 {
 114         if n%div == 0 {
 115             return false
 116         }
 117     }
 118     return true
 119 }