# Computing the Greatest Common Divisor of Two Positive Integers

### Problem Statement

The Greatest Common Divisor, GCD for short, of two positive integers can be computed with Euclid's division algorithm. Let the given numbers be a and b, a >= b. Euclid's division algorithm has the following steps:

1. Compute the remainder c of dividing a by b.
2. If the remainder c is zero, b is the greatest common divisor.
3. If c is not zero, replace a with b and b with the remainder c. Go back to step (1).
Write a program that reads in two integers and computes their greatest common divisor. Note that these two input could be in any order.

### Solution

! ---------------------------------------------------------
! This program computes the GCD of two positive integers
! using the Euclid method.  Given a and b, a >= b, the
! Euclid method goes as follows:  (1) dividing a by b yields
! a reminder c; (2) if c is zero, b is the GCD; (3) if c is
! no zero, b becomes a and c becomes c and go back to
! Step (1).  This process will continue until c is zero.
! ---------------------------------------------------------

PROGRAM  GreatestCommonDivisor
IMPLICIT  NONE

INTEGER   :: a, b, c

WRITE(*,*) 'Two positive integers please --> '
IF (a < b) THEN       ! since a >= b must be true, they
c = a              ! are swapped if a < b
a = b
b = c
END IF

DO                    ! now we have a <= b
c = MOD(a, b)      !    compute c, the reminder
IF (c == 0) EXIT   !    if c is zero, we are done.  GCD = b
a = b              !    otherwise, b becomes a
b = c              !    and c becomes b
END DO                !    go back

WRITE(*,*) 'The GCD is ', b

END PROGRAM  GreatestCommonDivisor

### Program Input and Output

• If the input values are 46332 and 71162, the computed GCD is 26.
46332  71162

The GCD is 26

• If the input values are 128 and 32, the GCD is 32.
128  32

The GCD is 32

• If the input values are 100 and 101, the GCD is 1 and 100 and 101 are relatively prime.
100  101

The GCD is 1

• If the input values are 97 and 97, the GCD is of course 97.
97  97

The GCD is 97

### Discussion

• Since there is no specific order for the two input values, it is possible that a may be less than b. In this case, these two values must be swapped.
• Thus, before entering the DO-loop, we are sure that a >= b holds.
• Then, the remainder is computed and stored to c. If c is zero, the program EXITs and displays the value of b as the GCD. The remainder is computed using Fortran intrinsic function MOD().
• If c is not zero, b becomes a and c becomes b, and reiterates.
• If we need to display the result as follows:
The GCD of 46332 and 71162 is 26

would the following change to the WRITE statement work?
WRITE(*,*) 'The GCD of ', a, ' and ', b, ' is ', b