| 1 | #!/bin/bash |
| 2 | # Optimized Sieve of Eratosthenes |
| 3 | # Script by Jared Martin, with very minor changes by ABS Guide author. |
| 4 | # Used in ABS Guide with permission (thanks!). |
| 5 | |
| 6 | # Based on script in Advanced Bash Scripting Guide. |
| 7 | # http://tldp.org/LDP/abs/html/arrays.html#PRIMES0 (ex68.sh). |
| 8 | |
| 9 | # http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf (reference) |
| 10 | # Check results against http://primes.utm.edu/lists/small/1000.txt |
| 11 | |
| 12 | # Necessary but not sufficient would be, e.g., |
| 13 | # (($(sieve 7919 | wc -w) == 1000)) && echo "7919 is the 1000th prime" |
| 14 | |
| 15 | UPPER_LIMIT=${1:?"Need an upper limit of primes to search."} |
| 16 | |
| 17 | Primes=( '' $(seq ${UPPER_LIMIT}) ) |
| 18 | |
| 19 | typeset -i i t |
| 20 | Primes[i=1]='' # 1 is not a prime. |
| 21 | until (( ( i += 1 ) > (${UPPER_LIMIT}/i) )) # Need check only ith-way. |
| 22 | do # Why? |
| 23 | if ((${Primes[t=i*(i-1), i]})) |
| 24 | # Obscure, but instructive, use of arithmetic expansion in subscript. |
| 25 | then |
| 26 | until (( ( t += i ) > ${UPPER_LIMIT} )) |
| 27 | do Primes[t]=; done |
| 28 | fi |
| 29 | done |
| 30 | |
| 31 | # echo ${Primes[*]} |
| 32 | echo # Change to original script for pretty-printing (80-col. display). |
| 33 | printf "%8d" ${Primes[*]} |
| 34 | echo; echo |
| 35 | |
| 36 | exit $? |