27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

fi<br />

let "t += $i "<br />

Primes[t]=$NON_PRIME<br />

# Tag as non−prime all multiples.<br />

done<br />

let "i += 1"<br />

done<br />

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

}<br />

# Invoke the functions sequentially.<br />

initialize<br />

sift<br />

print_primes<br />

# This is what they call structured programming.<br />

echo<br />

exit 0<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− #<br />

# Code below line will not execute.<br />

# This improved version of the Sieve, by Stephane Chazelas,<br />

# executes somewhat faster.<br />

# Must invoke with command−line argument (limit of primes).<br />

UPPER_LIMIT=$1<br />

let SPLIT=UPPER_LIMIT/2<br />

# From command line.<br />

# Halfway to max number.<br />

Primes=( '' $(seq $UPPER_LIMIT) )<br />

i=1<br />

until (( ( i += 1 ) > SPLIT )) # Need check only halfway.<br />

do<br />

if [[ −n $Primes[i] ]]<br />

then<br />

t=$i<br />

until (( ( t += i ) > UPPER_LIMIT ))<br />

do<br />

Primes[t]=<br />

done<br />

fi<br />

done<br />

echo ${Primes[*]}<br />

exit 0<br />

Compare this array−based prime number generator with an alternative that does not use arrays, Example<br />

A−17.<br />

−−<br />

Chapter 26. Arrays 303

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!