# //////////////////////////////////////////////////////////
# // Name: Peter M. Maurer
# // Program: Sieve of Eratosthenes
# // Due: Never
# // Language: TCL
# //////////////////////////////////////////////////////////

# define the sieve data structure
set i 0
for {set i 0} {$i<1000} {incr i} {
    # everything is potentially prime until proven otherwise
    set Candidates($i) 1
}
# Neither 1 nor 0 is prime, so flag them off
set Candidates(0) 0
set Candidates(1) 0
# start the sieve with the integer 0
set i 0
while {$i<1000} {
        # advance to the next un-crossed out number.
        # this number must be a prime
        while {$i<1000 && $Candidates($i) == 0} {
        set i [expr {$i + 1}]
        }
        # insure against running off the end of the data structure
        if {$i<1000} {
                # cross out all multiples of the prime, starting with 2*p.
        for {set j 2} {($i*$j)<1000} {incr j} {
                                set Candidates([expr {$j * $i}])  0
                }
                # advance to the next candidate
        set i [expr {$i + 1}]

        }
}
# all uncrossed-out numbers are prime (and only those numbers)
# print all primes
for {set i 0} {$i<1000} {incr i} { 
    if {$Candidates($i) != 0} { 
        puts "$i is prime" 
    } 
}
