program primes2;
{$APPTYPE CONSOLE}
type
TSequence=class // Generic type for integer sequences
function next:integer;virtual;abstract; // "next" is just a placeholder here and isn't callable
end;
TPrime=class(TSequence) // TPrime inherits from TSequence
iIndex:integer; // store which prime number we are at
function next:integer;override; // function to calc and return next
constructor create; // constructor for object
end;
var
allprimes:array of integer; // Delphi has no class variables, only unit variables
prime:TPrime;
constructor TPrime.create;
begin
inherited;
iIndex:=0; // we start at the 0th prime, 2
end;
function TPrime.next:integer; // calc next prime
var
i:integer;
function isPrime(it:integer):boolean; // check if number is prime
var
n:integer; // a run variable
begin
result:=true; // is prime until prooven otherwise
n:=0; // start check at first prime
while (result) and (n<iIndex) and (Sqr(AllPrimes[n])<=it) do // go as long as prime^2 < tested
begin
if (it mod AllPrimes[n])=0 then // its dividiable
result:=false; // e.g. its no prime
n:=n+1;
end;
end;
begin
i:=AllPrimes[iIndex]+1; // start after prime at index
iIndex:=iIndex+1; // move index to slot n+1
while not IsPrime(i) do inc(i); // find next prime
SetLength(AllPrimes,iIndex+1); // make array big enough
AllPrimes[iIndex]:=i; // store prime
result:=i; // return prime
end;
procedure PrintNumbers(Seq:TSequence;Count:Integer);
begin
while Count>0 do
begin
Dec(Count);
Writeln(Seq.Next);
readln;
end;
end;
begin
SetLength(AllPrimes,1); // delphi dynamical arrays need manual length setting :-/
AllPrimes[0]:=2; // include the 2
Prime:=TPrime.create; // create a prime object
PrintNumbers(Prime,1000); // print the 1000 primes after 2
Prime.Free; // free the prime object
end.