(* The Great Win32 Language Shootout http://dada.perl.it/shootout/

   contributed by Isaac Gouy (Modula2 novice)

   To build: xc =m sieve
   To run:   sieve 900
*)

MODULE Sieve;
<* m2extensions + *>
<* checkindex - *>
<* coverflow - *>

(* Prefer unqualified procedures *)
FROM LanguageShootout IMPORT N;

FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM SYSTEM IMPORT ADR, FILL;


CONST
   start = 2;
   stop = 8192;

TYPE Boolean_Array = ARRAY [start..stop] OF BOOLEAN;

VAR
   array_size: CARDINAL;
   n, count, i, k: CARDINAL;
   isPrimeNumber: Boolean_Array;

BEGIN
   n := N();
   array_size := SIZE(Boolean_Array);

   WHILE n > 0 DO
      DEC(n);
      count := 0;

      (* Set all the isPrimeNumber array to TRUE *)
      FILL( ADR(isPrimeNumber), TRUE, array_size );

      FOR i := start TO stop DO
         IF isPrimeNumber[i] THEN
	    INC(count);
            k := i+i;
            WHILE k <= stop DO
               isPrimeNumber[k] := FALSE;
	       INC(k, i);
            END;
         END;
      END;
   END;  	

   WriteString("Count:"); WriteCard(count,0); WriteLn;
END Sieve.