LeetCode icon indicating copy to clipboard operation
LeetCode copied to clipboard

Improve on find_gcd() on [Fortran] for problem 0255

Open ja72 opened this issue 4 years ago • 0 comments

Yes Fortran can accept an undeclared size array as an argument, reducing the "ceremony" needed

integer function find_gcd(nums)
integer, intent(in) :: nums(:)
    find_gcd = gcd(minval(nums), maxval(nums))
end function

Also, a working program can be declared that declares and calls gcd() in a single file, without having to define modules etc.

Below is some skeleton code for how to do this:

program LeetCode_0255
implicit none
integer, allocatable :: array(:)

array = [2, 5, 6, 9,10]    
print *, find_gcd(array)

contains
    
integer function find_gcd(nums)
integer, intent(in) :: nums(:)
    find_gcd = gcd(minval(nums), maxval(nums))
end function
    
function gcd(m, n) result(answer)
    integer, intent(in)  :: m, n
    integer              :: answer, irest, ifirst

    ifirst = iabs(m)
    answer = iabs(n)
    if (answer == 0) then
        answer = ifirst
    else
        do
            irest = mod(ifirst, answer)
            if (irest == 0)  exit
            ifirst = answer
            answer = irest
        enddo
        answer = iabs(answer)
    endif
end function 
end program 

Note that since the program declares implicit none, it can be omitted from the function definitions.

ja72 avatar Nov 17 '21 20:11 ja72