program gcd;
var a, b, answer : integer;
function gcd (a,b : integer) : integer;
var remainder: integer;
begin
while not (b=0) do
begin
remainder := a mod b;
a := b;
b := remainder;
end;
gcd :=a;
end;
begin
writeln ('To find the greatest common divisor enter two integers:');
readln (a);
readln (b);
answer := gcd(a,b);
writeln ('gcd is ', answer);
readln;
end.
For example: 24 and 102:
b not zero so remainder := 24 mod 102 = 24
a:= 102, b:= 24
b not zero so remainder := 102 mod 24 = 6 (note how 24 and 102 have been
reversed)
a:= 24, b:= 6
b not zero so remainder := 24 mod 6 = 0
a:= 6, b:=0
b = 0 so finish loop
gcd = a = 6
The variable b acts as a sentinel at the beginning of the while loop. The loop is only entered if b > 0. Also, a and b should be positive integers (it does not matter which is larger). This is the loop invariant. We should test user input for negative and real numbers. The assertion at the end of the loop is that b=0 and a is a positive integer >= 1.
Note that a and b have global scope, they are declared in the main program section, while remainder has local scope, it exists only while the function gcd exists. If we declared a and b inside the gcd function the variables a and b in the main section would be unaffected by changes to those inside the function. We cannot access the variable remainder from outside the function because when outside the function it does not exist.