program Primetester_Sieve; 
// http://primes.utm.edu/glossary/page.php?sort=SieveOfEratosthenes
{The most efficient way to find all of the small primes (say all those less 
 than 10,000,000) is by using a sieve such as Sieve of Eratosthenes(ca 240 BC):
 Make a list of all the integers less than or equal to n (and greater than one).
 Strike out the multiples of all primes less than or equal to the square root
 of n, then the numbers that are left are the primes.} 

const
 PRIMEFILE = 'primetest_thieves.txt';
 N = 7919;        //to test 1000: 7919  or 666: 4973 cks:23          

Type TAprime = array[1..N] of boolean;

//globals
var                                          
  mylist: TStringList; //is an object of class TStringList!
  beforeTime, afterTime: string;
  aprime: TAprime;

procedure checkEratosthenes(var vprime: TAprime); 
var 
  i,k: LONGINT;
BEGIN
  FOR i:= 2 TO N DO vprime[i]:= TRUE;
  FOR i:= 2 TO trunc(sqrt(N)) DO BEGIN
    k:= i;
    IF vprime[i] = TRUE THEN REPEAT
      k:= k+i;
      if k < N then
      vprime[k]:= FALSE;
    UNTIL k >= N;
  END;
END;

procedure StorePrimes;
var i, ctr: integer;
begin
  ctr:= 0;
  for i:= 2 to N do begin
    if aprime[i] then begin
      inc(ctr)
      //WRITELN(inttostr(ctr)+': '+inttostr(i))
      mylist.add(inttostr(ctr)+': '+inttostr(i));
    end;  
  end;  
end;

//main program
begin
  beforeTime:= Now;
  mylist:= TStringList.create;
    checkEratosthenes(aprime); 
    StorePrimes;
  afterTime:= Now;
  writeln('start: '+ beforeTime + ' from: '+intToStr(0))
  writeln('stop: ' + afterTime + ' to: '+intToStr(N))
  mylist.add(memo2.text)
  mylist.saveToFile(PRIMEFILE)
  //memo2.lines.loadFromFile(PRIMEFILE)
  mylist.Free;
end.