/* The MIT License (MIT) Copyright © 2020-2025 pacman64 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Single-file source-code for primes. To compile a smaller-sized command-line app, you can use the `go` command as follows: go build -ldflags "-s -w" -trimpath primes.go */ package main import ( "bufio" "math" "os" "strconv" ) // Note: the code is avoiding using the fmt package to save hundreds of // kilobytes on the resulting executable, which is a noticeable difference. const info = ` primes [options...] [count...] Show the first few prime numbers, starting from the lowest and showing one per line. When not given how many primes to find, the default is 1 million. All (optional) leading options start with either single or double-dash: -h show this help message -help show this help message ` func main() { howMany := 1_000_000 if len(os.Args) > 1 { switch os.Args[1] { case `-h`, `--h`, `-help`, `--help`: os.Stderr.WriteString(info[1:]) return } n, err := strconv.Atoi(os.Args[1]) if err != nil { os.Stderr.WriteString("\x1b[31m") os.Stderr.WriteString(err.Error()) os.Stderr.WriteString("\x1b[0m\n") os.Exit(1) } if n < 0 { n = 0 } howMany = n } primes(howMany) } func primes(left int) { bw := bufio.NewWriter(os.Stdout) defer bw.Flush() // 24 bytes are always enough for any 64-bit integer var buf [24]byte // 2 is the only even prime number if left > 0 { bw.WriteString("2\n") left-- } for n := uint64(3); left > 0; n += 2 { if oddPrime(n) { bw.Write(strconv.AppendUint(buf[:0], n, 10)) if err := bw.WriteByte('\n'); err != nil { // assume errors come from closed stdout pipes return } left-- } } } // oddPrime assumes the number given to it is odd func oddPrime(n uint64) bool { max := uint64(math.Sqrt(float64(n))) for div := uint64(3); div <= max; div += 2 { if n%div == 0 { return false } } return true }