primes.sh

来自「Shall高级编程」· Shell 代码 · 共 47 行

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

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?