Skip to content

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

@ja72

Description

@ja72

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions