Greatest common divisor

From Free Pascal wiki
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

English (en) suomi (fi) français (fr) polski (pl) русский (ru)

The greatest common divisor of two integers is the largest integer that divides them both. If numbers are 121 and 143 then greatest common divisor is 11.

There are many methods to calculate this. For example, the division-based Euclidean algorithm version may be programmed:

function greatestCommonDivisor

function greatestCommonDivisor(a, b: Int64): Int64;
var
  temp: Int64;
begin
  while b <> 0 do
  begin
    temp := b;
    b := a mod b;
    a := temp
  end;
  result := a;
end;

function greatestCommonDivisor_euclidsSubtractionMethod(a, b: Int64): Int64;
begin
  // only works with positive integers
  if (a < 0) then a := -a;
  if (b < 0) then b := -b;
  // don't enter loop, since subtracting zero won't break condition
  if (a = 0) then exit(b);
  if (b = 0) then exit(a);
  while not (a = b) do
  begin
    if (a > b) then
     a := a - b
    else
     b := b - a;
  end;
  result := a;
end;

see also

external references