#!/bin/sh # The MIT License (MIT) # # Copyright © 2024 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. # primes [options...] [count...] # # Find the first n prime numbers, emitting each one on its own line, with a # default of 100 thousand when not given a count. # # The help option is `-h`, `--h`, `-help`, or `--help`. # handle leading options case "$1" in -h|--h|-help|--help) awk '/^# +primes/, /^$/ { gsub(/^# ?/, ""); print }' "$0" exit 0 ;; esac awk ' BEGIN { left = 100 * 1000 if (ARGV[1] + 0 != 0) { left = ARGV[1] + 0 delete ARGV[1] } if (left < 0) { left = 0 } printf "showing first %d prime numbers\n", left > "/dev/stderr" if (left > 0) { print 2 left-- } for (n = 3; left > 0; n += 2) { if (is_prime(n)) { print n left-- } } exit } function is_prime(n, max, div) { if (n < 2) { return 0 } if (n % 2 == 0) { return n == 2 } max = sqrt(n) for (div = 3; div <= max; div += 2) { if (n % div == 0) { return 0 } } return 1 } ' "$@"