Delphi , program to print all prime numbers between 1 to N using while loop.

program FindPrimeNum;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Math,
  Classes,
  Windows;

  var
    i,j: integer;
    FStartTime: DWORD;
    f: Boolean;
    Lists: tstrings;
    Count, Last: Integer;
    PrimeList: array of integer;
begin
    Count:= 0;
    writeln ('program to print all prime numbers between 1 to N using while loop.');
    write('Number to find : ');
    try
       readln(Last);
    except
       on e:EInOutError do begin
           writeln ('Invalid number, system will changed to default value (100000)');
           Last:= 100000;
       end;
    end;
    //Last:= 500000;
    Writeln('find Prime from 2...'+format('%d',[Last]));
    Lists:= TStringList.create;
    FStartTime := GetTickCount;
    for i:= 2 to Last do begin
        j:= 0;
        f:= true;
        while ((high(PrimeList)>0) and (Power(PrimeList[j],2)<=i) and f=true) do begin
                f:= (i mod PrimeList[j] > 0);
                inc(j);
        end;

        if f=true then begin
           inc(Count);
           SetLength(PrimeList, Count);
           PrimeList[Count-1] := i;
        end;
    end;

    Writeln;
    Writeln(Format('...found prime numbers between 2..%d count: %d, %s: %f SEC.', [Last,
      Count, 'Time', ((GetTickCount - FStartTime)/1000) ]));
    Writeln('list of prime numbers...');
    for i := 0 to high(PrimeList) do begin
        write( format('%d,',[PrimeList[i]]) ) ; //show result to screen
        Lists.Add( format('%d,',[PrimeList[i]]) ) ;
    end;

    Lists.SaveToFile(extractfilepath(paramstr(0))+'PrimeNums.txt'); //write result to file
    Lists.Free;
    Writeln;
    Writeln(format('...Please see output file --> %s',[extractfilepath(paramstr(0))+'PrimeNums.txt']));
    writeln;
    writeln('press any key to exit...');

    Readln;
end.

Comments