Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ja72 opened this issue Nov 17, 2021 · 0 comments
Open

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

ja72 opened this issue Nov 17, 2021 · 0 comments

Comments

@ja72
Copy link

ja72 commented Nov 17, 2021

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 ja72 changed the title Improve on find_gcd() on [Fortran] Improve on find_gcd() on [Fortran] for problem 0255 Nov 17, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant