DelphiDabbler Code Snippets Database

Snippet Selection

The following snippets from the Code Snippets Database have been requested.

GCD

Determines the greatest common divisor of two given non-zero integers.

function GCD(A, B: Integer): Integer;
var
  Temp: Integer; // used in swapping A & B
begin
  while B <> 0 do
  begin
    Temp := B;
    B := A mod Temp;
    A := Temp;
  end;
  Result := Abs(A);
end;

GCD2

Determines the greatest common divisor of two given non-zero integers.

function GCD2(const A, B: Integer): Integer;
begin
  if B = 0 then
    Result := Abs(A)
  else
    Result := GCD2(B, A mod B);
end;

IsPrime

Checks if the given number is prime.

function IsPrime(N: Integer): Boolean;
var
  Max: Integer;     // max divisor
  Divisor: Integer; // different divisors to try
begin
  Result := False;
  if N < 2 then
    Exit; // not a prime
  Result := True;
  if N = 2 then
    Exit; // 2 is prime
  if N mod 2 = 0 then
    Result := False; // even numbers > 2 are not prime
  Max := Trunc(Sqrt(N)) + 1;
  Divisor := 3;
  // test odd numbers
  while (Max > Divisor) and Result do
  begin
    if (N mod Divisor) = 0 then
      Result := False;
    Inc(Divisor, 2); // next odd number
  end;
end;

IsPrime2

Checks if the given number is prime.

function IsPrime2(Val: Integer): Boolean;
var
  X: Integer; // index
begin
  Result := (Val > 1);
  if Result then
  begin
    for X := (Val div 2) downto 2 do
    begin
      Result := Result and ((Val mod X) <> 0);
      if not Result then
    	Break;
    end;
  end;
end;

LCD

Returns the least common divisor of two given non-zero integers.

function LCD(A, B: Integer): Integer;
begin
  Result := Abs((A * B)) div GCD(A, B);
end;

View the whole database.

Go to the DelphiDabbler website.