Mega Code Archive

 
Categories / Delphi / Examples
 

Getting the lowest common denominator

Question: How do I convert two numbers representing a ratio to a string that represents a fraction of the lowest common denominator? Answer: The following example demonstrates a technique based on equations originally solved by Euclid in approx. 300 B.C. : Example: function GetFracStr(Num1 : integer; Num2 : integer) : string; var N1 : integer; N2 : integer; Tmp : integer; begin if Num1 < Num2 then begin N1 := Num1; N2 := Num2; end else begin N1 := Num2; N2 := Num1; end; Tmp := N2 mod N1; while Tmp <> 0 do begin N2 := N1; N1 := Tmp; Tmp := N2 mod N1; end; result := IntToStr(Num1 div N1) + '/' + IntToStr(Num2 div N1); end; procedure TForm1.Button1Click(Sender: TObject); begin Memo1.Lines.Add(GetFracStr(2, 64)); end;