REM
REM Generating prime numbers lower than entered value.
REM
REM Using the Sieve algorithm - see http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
REM
REM PvE - September 2009 - GPL
REM Revised November 2009.
REM Revised May 2010.
REM

SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim

IF dim < 2 THEN
    PRINT "Usage: prime <number>"
    END
ENDIF

limit = VAL(arg$[1])

IF limit > 10000000 THEN
    PRINT "Numbers bigger than 10.000.000 are not supported."
    END
ENDIF

REM Create memory area
nr = MEMORY(limit)

REM Apply Sieve algorithm
counter = 2

REM Put address to '1' if not a prime
WHILE counter * counter < limit DO

    IF ISTRUE(PEEK(nr + counter)) THEN
        INCR counter
    ELSE
        FOR x = counter * 2 TO limit STEP counter
            POKE nr + x, 1
        NEXT
        INCR counter
    ENDIF

WEND

REM Print prime numbers
total = 0

FOR i = 2 TO limit - 1
    IF ISFALSE(PEEK(nr + i)) THEN
        PRINT i, " ";
        INCR total
    ENDIF
NEXT

REM Print results
PRINT NL$, NL$, "There are ", total, " prime numbers below ", limit, ".", NL$