BASH

Bash is one of many shell programs written for the UNIX/Linux environment. The first was just plain old sh written by K&R when they created UNIX. Steve Bourne created a significantly enhanced programmable shell that was also called sh and replaced the original sh. Then came vsh, esh, the Vi and Emacs shells and ksh the Korn shell that incorporated many of the features of both vsh and esh. And there was csh which could be programmed using C-like syntax. There was also adventure-shell that would treat each directory as a room containing treasures (i.e. files). I'm sure there were many, many others. Finally, there was the Bourne-again shell -- bash -- which I assume is an enhanced version of the old Bourne shell.

This program is an abuse of bash. Bash was never intended as a general purpose programming language, despite the fact that it can be used that way.

This was one of the most difficult implementations of this algorithm. I'm not sure why, but it just didn't want to work. It's also very slow. One can make the program executable and just run it, or one can type:

bash SieveE.sh

This program runs on Red Hat Linux 9.0 and on Red Hat Enterprise.


#//////////////////////////////////////////////////////////


#// Name: Peter M. Maurer


#// Program: Sieve of Eratosthenes


#// Due: Never


#// Language: bash


#//////////////////////////////////////////////////////////



# define the sieve data structure


declare -a candidates[1001] # protect against strict evaluation of booleans


# everything is potentially prime until proven otherwise


i=0


while [ $i -lt 1001 ]


do


candidates[i]=1


i=`expr $i + 1`


done


# Neither 1 nor 0 is prime, so flag them off


candidates[0]=0


candidates[1]=0


# start the sieve with the integer 0


i=0


while [ $i -lt 1000 ]


do


# advance to the next un-crossed out number.


# this number must be a prime


while [ $i -lt 1000 -a ${candidates[$i]} = 0 ]


do


i=`expr $i + 1`


done


if [ $i -lt 1000 ]


then


# // cross out all multiples of the prime, starting with 2*p.


j=2


k=`expr $i "*" $j`


while [ $k -lt 1000 ]


do


candidates[$k]=0


j=`expr $j + 1`


k=`expr $i "*" $j`


done


# // advance to the next candidate


i=`expr $i + 1`


fi


done


# // all uncrossed-out numbers are prime (and only those numbers)


# // print all primes


i=0


while [ $i -lt 1000 ]


do


if [ ${candidates[$i]} != 0 ]


then


echo $i " is prime"


fi


i=`expr $i + 1`


done

Click Here for the actual code.