unit Gcd1F;
//*******************************************************
// Example program demonstrating recursive GCDs.
//*******************************************************
// 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
  TGcd1Form = 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;
    Label4: TLabel;
    TimesLabel: TLabel;
    Label6: TLabel;
    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
  Gcd1Form: TGcd1Form;

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

implementation

var
    gcd_calls : Integer;

{$R *.DFM}

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

procedure TGcd1Form.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 TGcd1Form.CmdComputeClick(Sender: TObject);
var
    a, b : Longint;
begin
    gcd_calls := 0;
    a := StrToInt(AEdit.Text);
    b := StrToInt(BEdit.Text);
    ResultLabel.Caption := IntToStr(Gcd(a, b));
    TimesLabel.Caption  := IntToStr(gcd_calls);
end;

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

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

// Compute GCDs recursively.
function Gcd(a, b : Longint) : Longint;
var
    b_mod_a : Longint;
begin
    gcd_calls := gcd_calls + 1; // Count the function calls.

    b_mod_a := b mod a;
    if (b_mod_a = 0) then
        Gcd := a
    else
        Gcd := Gcd(b_mod_a, a);
end;

end.
