本例效果图:
代码文件:
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; Edit2: TEdit; procedure Button1Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} {求最大公约数 算法: 假如 x > y, x mod y 取余数后, y 付给 x、余数付给 y, 然后重复运算, 最后非 0 的余数就是最大公约数 } function zdgys(x,y: Cardinal): Cardinal; var n: Integer; begin n := y; if x < y then begin y := x; x := n; end; while n > 0 do begin n := x mod y; x := y; if n > 0 then y := n; end; Result := y; end; {求最小公倍数 算法: x * y div 它们的最大公约数 } function zxgbs(x,y: Cardinal): Cardinal; var m,n: Cardinal; begin m := x * y; n := y; if x < y then begin y := x; x := n; end; while n > 0 do begin n := x mod y; x := y; if n > 0 then y := n; end; Result := m div y; end; {测试} procedure TForm1.Button1Click(Sender: TObject); const str = '%0:d 与 %1:d 的最大公约数是 %2:d'#13#10'%0:d 与 %1:d 的最小公倍数是 %3:d'; var x,y,a,b: Cardinal; begin x := StrToIntDef(Edit1.Text, 1); y := StrToIntDef(Edit2.Text, 1); a := zdgys(x, y); b := zxgbs(x, y); ShowMessageFmt(str, [x,y,a,b]); end; end.
窗体文件:
object Form1: TForm1 Left = 0 Top = 0 Caption = 'Form1' ClientHeight = 160 ClientWidth = 268 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False PixelsPerInch = 96 TextHeight = 13 object Button1: TButton Left = 176 Top = 14 Width = 75 Height = 25 Caption = 'Button1' TabOrder = 0 OnClick = Button1Click end object Edit1: TEdit Left = 17 Top = 16 Width = 64 Height = 21 TabOrder = 1 Text = 'Edit1' end object Edit2: TEdit Left = 98 Top = 16 Width = 63 Height = 21 TabOrder = 2 Text = 'Edit2' end end