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.

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

let SPLIT=UPPER_LIMIT/2<br />

# Optimization:<br />

# Need to test numbers only halfway to upper limit.<br />

declare −a Primes<br />

# Primes[] is an array.<br />

initialize ()<br />

{<br />

# Initialize the array.<br />

i=$LOWER_LIMIT<br />

until [ "$i" −gt "$UPPER_LIMIT" ]<br />

do<br />

Primes[i]=$PRIME<br />

let "i += 1"<br />

done<br />

# Assume all array members guilty (prime)<br />

# until proven innocent.<br />

}<br />

print_primes ()<br />

{<br />

# Print out the members of the Primes[] array tagged as prime.<br />

i=$LOWER_LIMIT<br />

until [ "$i" −gt "$UPPER_LIMIT" ]<br />

do<br />

if [ "${Primes[i]}" −eq "$PRIME" ]<br />

then<br />

printf "%8d" $i<br />

# 8 spaces per number gives nice, even columns.<br />

fi<br />

let "i += 1"<br />

done<br />

}<br />

sift () # Sift out the non−primes.<br />

{<br />

let i=$LOWER_LIMIT+1<br />

# We know 1 is prime, so let's start with 2.<br />

until [ "$i" −gt "$UPPER_LIMIT" ]<br />

do<br />

if [ "${Primes[i]}" −eq "$PRIME" ]<br />

# Don't bother sieving numbers already sieved (tagged as non−prime).<br />

then<br />

t=$i<br />

while [ "$t" −le "$UPPER_LIMIT" ]<br />

do<br />

Chapter 26. Arrays 302

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

Saved successfully!

Ooh no, something went wrong!