LDP/LDP/guide/docbook/abs-guide/primes.sh

50 lines
1.4 KiB
Bash
Raw Normal View History

2001-07-10 14:25:50 +00:00
#!/bin/bash
2001-09-04 13:27:31 +00:00
# primes.sh: Generate prime numbers, without using arrays.
2002-04-01 16:04:17 +00:00
# Script contributed by Stephane Chazelas.
2001-07-10 14:25:50 +00:00
2002-06-17 13:17:07 +00:00
# This does *not* use the classic "Sieve of Eratosthenes" algorithm,
2008-03-13 13:24:45 +00:00
#+ but instead the more intuitive method of testing each candidate number
2001-10-15 14:21:41 +00:00
#+ for factors (divisors), using the "%" modulo operator.
2001-07-10 14:25:50 +00:00
2008-03-13 13:24:45 +00:00
LIMIT=1000 # Primes, 2 ... 1000.
2001-07-10 14:25:50 +00:00
Primes()
{
(( n = $1 + 1 )) # Bump to next integer.
2001-10-15 14:21:41 +00:00
shift # Next parameter in list.
# echo "_n=$n i=$i_"
2001-07-10 14:25:50 +00:00
if (( n == LIMIT ))
then echo $*
return
fi
2008-03-13 13:24:45 +00:00
for i; do # "i" set to "@", previous values of $n.
2001-10-15 14:21:41 +00:00
# echo "-n=$n i=$i-"
(( i * i > n )) && break # Optimization.
(( n % i )) && continue # Sift out non-primes using modulo operator.
2001-10-15 14:21:41 +00:00
Primes $n $@ # Recursion inside loop.
2001-07-10 14:25:50 +00:00
return
done
2008-11-23 22:43:47 +00:00
Primes $n $@ $n # Recursion outside loop.
# Successively accumulate
#+ positional parameters.
# "$@" is the accumulating list of primes.
2001-07-10 14:25:50 +00:00
}
Primes 1
2008-11-23 22:43:47 +00:00
exit $?
# Pipe output of the script to 'fmt' for prettier printing.
2001-07-10 14:25:50 +00:00
2003-11-03 16:25:16 +00:00
# Uncomment lines 16 and 24 to help figure out what is going on.
2001-10-15 14:21:41 +00:00
2003-11-03 16:25:16 +00:00
# Compare the speed of this algorithm for generating primes
#+ with the Sieve of Eratosthenes (ex68.sh).
2001-09-04 13:27:31 +00:00
2008-03-13 13:24:45 +00:00
2008-11-23 22:43:47 +00:00
# Exercise: Rewrite this script without recursion.