home *** CD-ROM | disk | FTP | other *** search
- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
- ;;; This production system implements the Sieve of Eratosthenes. It
- ;;; uses a vector attribute to store the values of the primes as they
- ;;; are found.
-
-
- ;;;;;;;;;;;;;;;;;;;;; data structures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
- ;;;
- ;;; (table n) (target n) (remove-mult x y z)
- ;;;
- (literalize primes
- current
- prime-list)
-
- (vector-attribute prime-list)
-
- ;;;;;;;;;;;;;;;;;;; Table Making ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
- (p end-table (table 1)
- (target)
- -->
- (remove 1)
- (remove 2)
- (make primes ^current 2 ^prime-list 1 ))
-
- (p make-table (target {<n> > 0})
- -->
- (make table <n>)
- (modify 1 ^2 (compute <n> - 1)))
-
- ;;;;;;;;;;;;;;;;;;; Find Primes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
- (p last-prime (primes ^current <x>)
- (to-num <= <x>)
- -(table <x>)
- -(remove-mult)
- -->
- (make done-primes))
-
- (p got-prime (primes ^current <x>)
- (table <x>)
- -(remove-mult)
- -->
- (remove 2)
- (remove 1)
- (make primes (compute (<x> + 1)) (substr 1 prime-list inf) <x>)
- (make remove-mult (compute <x> * <x>) <x> <x>))
-
- (p not-prime (primes ^current <x>)
- (to-num > <x>)
- -(table <x>)
- -(remove-mult)
- -->
- (modify 1 ^current (compute <x> + 1)))
-
- ;;;;;;;;;;;;;;;;;;; Remove Multiples ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
- (p end-remove (remove-mult <x>)
- (to-num <= <x>)
- -->
- (remove 1))
-
- (p mult-remove (remove-mult <x> <y> <z>)
- (table <x>)
- -->
- (remove 2)
- (remove 1)
- (make remove-mult (compute (<y> * (<z> + 1))) <y> (compute (<z> + 1))))
-
- (p incr-remove (remove-mult <x> <y> <z>)
- (to-num > <x>)
- -(table <x>)
- -->
- (remove 1)
- (make remove-mult (compute (<y> * (<z> + 1))) <y> (compute (<z> + 1))))
-
- ;;;;;;;;;;;;;;;;;;; I/O Productions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
- (p output-results (done-primes)
- (to-num <y>)
- (primes)
- -->
- (remove 1)
- (remove 2)
- (remove 3)
- (write (crlf) "The Primes from 1 to " <y> " are: "
- (crlf) (substr 3 prime-list inf))
- (make enter-to-num))
-
- (p sieve-start (start)
- -->
- (write "Program to compute the primes from 1 to a number entered"
- (crlf) "by the user."
- (crlf))
- (remove 1)
- (make enter-to-num))
-
- (p sieve (enter-to-num) -->
- (remove 1)
- (write (crlf)
- "Enter a positive number to compute the primes between"
- (crlf)
- "1 and that number, or enter a negative number or 0 to quit"
- (crlf))
- (bind <x> (accept))
- (make to-num <x>)
- (make target <x>))
-
- ;;;;;;;;;;;;;;;;;;; end of productions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;