(* Collection of code snippets by Arne Vajhøj *)
(* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) *)
program perfect;

{$APPTYPE CONSOLE}

uses
  Windows, SysUtils;

function IsPerfect(n : integer) : boolean;

var
  na, i, sum : integer;
  a : array [0..10000] of integer;

begin
   na := 0;
   for i := 1 to (n div 2 + 1) do begin
      if (n mod i) = 0 then begin
         a[na] := i;
         inc(na);
      end;
   end;
   sum := 0;
   for i := 0 to (na - 1) do begin
     sum := sum + a[i];
   end;
   IsPerfect := (sum = n);
end;

function IsPerfectOpt(n : integer) : boolean;

var
  sqrtn, na, i, sum : integer;
  a : array [0..10000] of integer;

begin
   sqrtn := trunc(sqrt(n));
   na := 0;
   a[na] := 1;
   inc(na);
   for i := 2 to sqrtn do begin
      if (n mod i) = 0 then begin
         a[na] := i;
         inc(na);
         a[na] := n div i;
         inc(na);
      end;
   end;
   sum := 0;
   for i := 0 to (na - 1) do begin
     sum := sum + a[i];
   end;
   IsPerfectOpt := (sum = n);
end;

const
   maxbits = 16;

var
   bitfit : array [1..maxbits] of integer;

function IsPerfectMoreOpt(n : integer) : boolean;

var
   i : integer;
   candidate : boolean;

begin
   candidate := false;
   for i := 1 to maxbits do begin
      if bitfit[i] = n then candidate := true;
   end;
   if candidate then
      IsPerfectMoreOpt := IsPerfectOpt(n)
   else
      IsPerfectMoreOpt := false;
end;

var
  i, t1, t2, t3, t4 : integer;

begin
  bitfit[1] := 1;
  for i := 2 to maxbits do bitfit[i] := (bitfit[i-1] shl 1) + 1;
  for i := 1 to maxbits do bitfit[i] := bitfit[i] shl (i - 1);
  t1 := GetTickCount;
  (*
  for i := 1 to 10000 do begin
    if IsPerfect(i) then begin
      writeln(i);
    end;
  end;
  t2 := GetTickCount;
  for i := 1 to 10000 do begin
    if IsPerfectOpt(i) then begin
      writeln(i);
    end;
  end;
  t3 := GetTickCount;
  for i := 1 to 10000 do begin
    if IsPerfectMoreOpt(i) then begin
      writeln(i);
    end;
  end;
  t4 := GetTickCount;
  writeln(t2-t1,' ',t3-t2,' ',t4-t3);
  *)
  for i := 1 to 100000000 do begin
    if IsPerfectMoreOpt(i) then begin
      writeln(i);
    end;
  end;
end.
