File: primes.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 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 To compile a smaller-sized command-line app, you can use the `go` command as
  27 follows:
  28 
  29 go build -ldflags "-s -w" -trimpath primes.go
  30 */
  31 
  32 package main
  33 
  34 import (
  35     "bufio"
  36     "math"
  37     "os"
  38     "strconv"
  39 )
  40 
  41 // Note: the code is avoiding using the fmt package to save hundreds of
  42 // kilobytes on the resulting executable, which is a noticeable difference.
  43 
  44 const info = `
  45 primes [options...] [count...]
  46 
  47 
  48 Show the first few prime numbers, starting from the lowest and showing one
  49 per line. When not given how many primes to find, the default is 1 million.
  50 
  51 All (optional) leading options start with either single or double-dash:
  52 
  53     -h          show this help message
  54     -help       show this help message
  55 `
  56 
  57 func main() {
  58     howMany := 1_000_000
  59     if len(os.Args) > 1 {
  60         switch os.Args[1] {
  61         case `-h`, `--h`, `-help`, `--help`:
  62             os.Stderr.WriteString(info[1:])
  63             return
  64         }
  65 
  66         n, err := strconv.Atoi(os.Args[1])
  67         if err != nil {
  68             os.Stderr.WriteString("\x1b[31m")
  69             os.Stderr.WriteString(err.Error())
  70             os.Stderr.WriteString("\x1b[0m\n")
  71             os.Exit(1)
  72         }
  73 
  74         if n < 0 {
  75             n = 0
  76         }
  77         howMany = n
  78     }
  79 
  80     primes(howMany)
  81 }
  82 
  83 func primes(left int) {
  84     bw := bufio.NewWriter(os.Stdout)
  85     defer bw.Flush()
  86 
  87     // 24 bytes are always enough for any 64-bit integer
  88     var buf [24]byte
  89 
  90     // 2 is the only even prime number
  91     if left > 0 {
  92         bw.WriteString("2\n")
  93         left--
  94     }
  95 
  96     for n := uint64(3); left > 0; n += 2 {
  97         if oddPrime(n) {
  98             bw.Write(strconv.AppendUint(buf[:0], n, 10))
  99             if err := bw.WriteByte('\n'); err != nil {
 100                 // assume errors come from closed stdout pipes
 101                 return
 102             }
 103             left--
 104         }
 105     }
 106 }
 107 
 108 // oddPrime assumes the number given to it is odd
 109 func oddPrime(n uint64) bool {
 110     max := uint64(math.Sqrt(float64(n)))
 111     for div := uint64(3); div <= max; div += 2 {
 112         if n%div == 0 {
 113             return false
 114         }
 115     }
 116     return true
 117 }