Solution Homework 0 Feb-07

The most efficient solution to this problem is the so called "Sieve of Eratosthenes". For more information on prime numbers and the method see:
Sieve of Eratosthenes

another nice one is :
Prime number theorem

See the solutions provided by the seminar members (all scripts are working properly) for comparision:

arthur
kornel
qin
stan

Sieve of Eratosthenes download here

#!/usr/local/bin/wish -f
# ===============================================================
#  JANUS-SR   Janus Speech Recognition Toolkit
#             ---------------------------------------------------
#             Advanced Lab Speech Recognition and Understanding
#
#  Author   : tanja@cs.cmu.edu
#  Module   : Eratosthenes.tcl
#  Date     : Feb 07 2001
# 
#  Remarks  : determines the first N primes
#  
# ===============================================================
# N should be 100
# Prime number theorem says that for large n the density of primes is n/log n
# (see http://www-groups.dcs.st-and.ac.uk/~history/HistTopics/Prime_numbers.html)
# setting n = 1000 we should be on the save side

# ------------------------
#  initialize
# ------------------------
set n 1000
set a(1) 1
for {set i 2} {$i <= $n} {incr i} {
    set a($i) 1
}

# ------------------------
#  walk thru the sieve
# ------------------------
set p 2
while {[expr $p * $p] <= $n} {
    set j [expr $p * 2]
    while {$j <= $n} {
	set a($j) 0
	set j [expr $j + $p]
    }
    incr p
    while {$a($p) == 0} {
	incr p 
    }
}

# ------------------------
#  output the first 100
# ------------------------
set cnt 1
for {set i 2} {$i < $n} {incr i} {
    if {$a($i) == 1} {puts "${cnt}. prime: $i"; incr cnt} 
    if {$cnt > 100} {exit}
}
exit

Last modified: Fri Feb 23 11:30:07 EST 2001
Maintainer: tanja@cs.cmu.edu.