This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.


The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.



Task

Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.

That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.

If there's an easy way to add such a wheel based optimization, implement it as an alternative version.



Note

 It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.


Related tasks

   Emirp primes
   count in factors
   prime decomposition
   factors of an integer
   extensible prime generator
   primality by trial division
   factors of a Mersenne number
   trial factoring of a Mersenne number
   partition an integer X into N primes
   sequence of primes by Trial Division


100H:
 
DECLARE PRIME$MAX LITERALLY '5000';
 
/* CREATE SIEVE OF GIVEN SIZE */
MAKE$SIEVE: PROCEDURE(START, SIZE);
    DECLARE (START, SIZE, M, N) ADDRESS;
    DECLARE PRIME BASED START BYTE;
 
    PRIME(0)=0; /* 0 AND 1 ARE NOT PRIMES */
    PRIME(1)=0; 
    DO N=2 TO SIZE;
        PRIME(N)=1; /* ASSUME ALL OTHERS ARE PRIME AT BEGINNING */
    END;
 
    DO N=2 TO SIZE;
        IF PRIME(N) THEN DO; /* IF A NUMBER IS PRIME... */
            DO M=N*N TO SIZE BY N;
                PRIME(M) = 0; /* THEN ITS MULTIPLES ARE NOT */
            END;
        END;
    END;
END MAKE$SIEVE;
 
/* CP/M CALLS */
BDOS: PROCEDURE(FUNC, ARG);
    DECLARE FUNC BYTE, ARG ADDRESS;
    GO TO 5;
END BDOS;
 
DECLARE BDOS$EXIT  LITERALLY '0',
        BDOS$PRINT LITERALLY '9';
 
/* PRINT A 16-BIT NUMBER */
PRINT$NUMBER: PROCEDURE(N);
    DECLARE (N, P) ADDRESS;
    DECLARE S (8) BYTE INITIAL ('.....',10,13,'$');
    DECLARE C BASED P BYTE;
    P = .S(5);
DIGIT:
    P = P - 1;
    C = (N MOD 10) + '0';
    N = N / 10;
    IF N > 0 THEN GO TO DIGIT;
    CALL BDOS(BDOS$PRINT, P);
END PRINT$NUMBER;
 
/* PRINT ALL PRIMES UP TO N */
PRINT$PRIMES: PROCEDURE(N, SIEVE);
    DECLARE (I, N, SIEVE) ADDRESS;
    DECLARE PRIME BASED SIEVE BYTE;
    CALL MAKE$SIEVE(SIEVE, N);
    DO I = 2 TO N;
        IF PRIME(I) THEN CALL PRINT$NUMBER(I);
    END;
END PRINT$PRIMES;
 
CALL PRINT$PRIMES(PRIME$MAX, .MEMORY);
 
CALL BDOS(BDOS$EXIT, 0);
EOF