Debian Codegraph @

primes.sh

raw symbols SCIP
1 #!/bin/bashscip-shell filesystem . . `/bin/bash`.
2 # primes.sh: Generate prime numbers, without using arrays.
3 # Script contributed by Stephane Chazelas.
4
5 # This does *not* use the classic "Sieve of Eratosthenes" algorithm,
6 #+ but instead the more intuitive method of testing each candidate number
7 #+ for factors (divisors), using the "%" modulo operator.
8
9
10 LIMIT=1000 # Primes, 2 ... 1000.
11
12 Primesscip-shell shell abs-guide 10-4 Primes().()
13 {
14 (( n = $1 + 1 )) # Bump to next integer.
15 shift # Next parameter in list.
16 # echo "_n=$n i=$i_"
17
18 if (( n == LIMIT ))
19 then echoscip-shell system . . echo. $*
20 return
21 fi
22
23 for i; do # "i" set to "@", previous values of $n.
24 # echo "-n=$n i=$i-"
25 (( i * i > n )) && break # Optimization.
26 (( n % i )) && continue # Sift out non-primes using modulo operator.
27 Primesscip-shell shell abs-guide 10-4 Primes(). $n $@ # Recursion inside loop.
28 return
29 done
30
31 Primesscip-shell shell abs-guide 10-4 Primes(). $n $@ $n # Recursion outside loop.
32 # Successively accumulate
33 #+ positional parameters.
34 # "$@" is the accumulating list of primes.
35 }
36
37 Primesscip-shell shell abs-guide 10-4 Primes(). 1
38
39 exit $?
40
41 # Pipe output of the script to 'fmt' for prettier printing.
42
43 # Uncomment lines 16 and 24 to help figure out what is going on.
44
45 # Compare the speed of this algorithm for generating primes
46 #+ with the Sieve of Eratosthenes (ex68.sh).
47
48
49 # Exercise: Rewrite this script without recursion.