gcd Function

public elemental function gcd(a, b)

Arguments

Type IntentOptional Attributes Name
integer, intent(in) :: a
integer, intent(in) :: b

Return Value integer


Source Code

   ELEMENTAL FUNCTION gcd(a, b)
      INTEGER, INTENT(IN)                                :: a, b
      INTEGER                                            :: gcd

      INTEGER                                            :: aa, ab, l, rem, s

      aa = ABS(a)
      ab = ABS(b)
      IF (aa < ab) THEN
         s = aa
         l = ab
      ELSE
         s = ab
         l = aa
      END IF
      IF (s .NE. 0) THEN
         DO
            rem = MOD(l, s)
            IF (rem == 0) EXIT
            l = s
            s = rem
         END DO
         GCD = s
      ELSE
         GCD = l
      END IF
   END FUNCTION gcd