unit Gcd2F;
//*******************************************************
// Example program demonstrating non-recursive GCDs
// using tail recursion removal.
//*******************************************************
// Copyright (C) 1998 John Wiley & Sons, Inc.
// All rights reserved. See additional copyright
// information in Readme.txt.
//*******************************************************

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, Menus;

type
  TGcdForm = class(TForm)
    MainMenu1: TMainMenu;
    File1: TMenuItem;
    mnuExit: TMenuItem;
    Help1: TMenuItem;
    mnuAbout: TMenuItem;
    AEdit: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    ResultLabel: TLabel;
    CmdCompute: TButton;
    Label3: TLabel;
    BEdit: TEdit;
    procedure NumbersChanged(Sender: TObject);
    procedure NumbersOnly(Sender: TObject; var Key: Char);
    procedure CmdComputeClick(Sender: TObject);
    procedure mnuExitClick(Sender: TObject);
    procedure mnuAboutClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  GcdForm: TGcdForm;

    function Gcd(a, b : Longint) : Longint;

implementation

{$R *.DFM}

procedure TGcdForm.NumbersChanged(Sender: TObject);
begin
    CmdCompute.Enabled :=
        ((AEdit.Text <> '') and (BEdit.Text <> ''));
end;

procedure TGcdForm.NumbersOnly(Sender: TObject; var Key: Char);
begin
    if (Key = #8) then exit; // Backspace.
    if ((Key >= '0') and (Key <= '9')) then exit;
    Key := #0;
end;

procedure TGcdForm.CmdComputeClick(Sender: TObject);
var
    a, b : Longint;
begin
    a := StrToInt(AEdit.Text);
    b := StrToInt(BEdit.Text);
    ResultLabel.Caption := IntToStr(Gcd(a, b));
end;

procedure TGcdForm.mnuExitClick(Sender: TObject);
begin
    Close;
end;

procedure TGcdForm.mnuAboutClick(Sender: TObject);
const
    CRCR = #13#10#13#10;
begin
    MessageDlg(
        'This program uses tail recursion removal to compute the greatest common divisor of two numbers non-recursively.' + CRCR +
        'Enter values for A and B and click the Compute button to calculate GCD(A, B).'
        , mtInformation, [mbOK], 0);
end;

// Use tail recursion removal to compute GCDs non-recursively.
function Gcd(a, b : Longint) : Longint;
var
    b_mod_a : Longint;
begin
    b_mod_a := b mod a;
    while (b_mod_a <> 0) do
    begin
        // Prepare the arguments for "recursion."
        b := a;
        a := b_mod_a;
        b_mod_a := b mod a;
    end;
    Gcd := a;
end;

end.
