Sieve of Eratosthenes

From Rosetta Code
Revision as of 23:46, 18 October 2007 by rosettacode>IanOsgood (add Forth)
Task
Sieve of Eratosthenes
You are encouraged to solve this task according to the task description, using any language you may know.

The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

Forth

: sieve ( n -- ) \ find primes up to n
  here over erase
  dup 2 do
    here i + c@ 0= if
      i dup .
      begin  i +  2dup >
      while  1 over here + c!
      repeat drop
    then
  loop drop ;

100 sieve


MAXScript

fn eratosthenes n =
(
    multiples = #()
    print 2
    for i in 3 to n by 2 do
    (
        if (findItem multiples i) == 0 then
        (
            print i
            for j in (i + i) to n by i do
            (
                append multiples j
            )
        )
    )
)

eratosthenes 100

Python

def eratosthenes(n):
    multiples = []
    print 2
    for i in xrange(3, n, 2):
        if not i in multiples:
            print i
            for j in xrange((i+i), n, i):
                multiples.append(j)

eratosthenes(100)