unit primosF;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  ComCtrls, Spin;

type
  { TAnadePrimo }

  TAnadePrimo= class (TThread)
    private
    FMax, FTotal, FPosicion: Integer;
  protected
    procedure Execute; override;
    procedure MostrarTotal;
    procedure ActualizarProgreso;
  public
    property Max: Integer read FMax write FMax;
end;

type

  { TForm1 }

  TForm1 = class(TForm)
    Calculo: TButton;
    Label1: TLabel;
    LBPrimos: TListBox;
    ProgressBar1: TProgressBar;
    seNumero: TSpinEdit;
    procedure CalculoClick(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}
function esPrimo(const n: int64): boolean;
var
i: cardinal;
en: extended;
begin
  if n <> 2 then begin
  en := n;
  for i := 2 to round(sqrt(en)) do
      if n mod i = 0 then begin
      result := false;
      exit;
      end;
  end;
result := n > 0;
end;

{ TAnadePrimo }

procedure TAnadePrimo.Execute;
var
  I: Integer;
begin
  FMax:= Form1.seNumero.Value;

  for I := 1 to FMax do
  begin
    if esPrimo (I) then
     begin
      FTotal:=I;
      Synchronize (@MostrarTotal) ;
     end ;
  end;
    if  FMax mod I  = 0 then
    begin
	FPosicion := I * 100 div FMax;
	Synchronize (@ActualizarProgreso) ;
    end ;
end;

procedure TAnadePrimo.MostrarTotal;
begin

Form1.LBPrimos.Items.Add (inttostr(FTotal));
end;

procedure TAnadePrimo.ActualizarProgreso;
begin
 Form1.ProgressBar1.Position := FPosicion;
end;

{ TForm1 }

procedure TForm1.CalculoClick(Sender: TObject);
  var
  AnadirHilo: TAnadePrimo;
begin
 LBPrimos.Items.Clear;
 ProgressBar1.Position := 0;
  AnadirHilo := TAnadePrimo.Create (True) ;
  AnadirHilo.FreeOnTerminate:= true;
  AnadirHilo.Max := Form1.seNumero.Value;

  AnadirHilo.Start;

end;
end.



