From b70d57b1bb12cfb5b5923537cc1615fd268aecd9 Mon Sep 17 00:00:00 2001 From: Igor Pashev Date: Tue, 20 Sep 2022 20:36:13 +0200 Subject: Update Fortran --- gcd.f03 | 56 -------------------------------------------------------- gcd.f90 | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 56 deletions(-) delete mode 100644 gcd.f03 create mode 100644 gcd.f90 diff --git a/gcd.f03 b/gcd.f03 deleted file mode 100644 index c2c585d..0000000 --- a/gcd.f03 +++ /dev/null @@ -1,56 +0,0 @@ -! SYNOPSIS: -! -! # gfortran -o gcd-f gcd.f03 -! # ./gcd-f 11 22 33 121 -! - -program GCD - implicit none - - integer, allocatable :: ns(:) - integer :: i, n - character*20 :: tmpstr - - n = command_argument_count() - - allocate (ns(n)) ! allocate memory for numbers given in command line - - do i = 1, n - call get_command_argument(i, tmpstr) - ns(i) = str2int(tmpstr) - end do - - print *, gcdn(ns) - - deallocate (ns) - -! If we declare functions first, -! we have to specify its types within -! the `program' section. -! See http://en.wikibooks.org/wiki/Fortran/Fortran_procedures_and_functions -contains - - pure integer function str2int(s) - character*(*), intent(in) :: s - read (s, *) str2int - end function - - pure recursive integer function gcd2(a, b) result(GCD) - integer, intent(in) :: a, b - if (b == 0) then - GCD = a - else - GCD = gcd2(b, mod(a, b)) - end if - end function gcd2 - - pure integer function gcdn(n) - integer, intent(in) :: n(:) ! n is an array - integer :: i - gcdn = n(1) - do i = 2, size(n) - gcdn = gcd2(gcdn, n(i)) - end do - end function - -end program diff --git a/gcd.f90 b/gcd.f90 new file mode 100644 index 0000000..c17c61c --- /dev/null +++ b/gcd.f90 @@ -0,0 +1,52 @@ +! SYNOPSIS: +! +! # gfortran -o gcd-f gcd.f90 +! # ./gcd-f 11 22 33 121 +! + +program GCD + implicit none + + integer, allocatable :: ns(:) + integer :: i, n + character(len=20) :: tmpstr + + n = command_argument_count() + + allocate (ns(n)) + + do i = 1, n + call get_command_argument(i, tmpstr) + ns(i) = str2int(tmpstr) + end do + + print '(I0)', gcdn(ns) + + deallocate (ns) + +contains + + pure integer function str2int(s) + character*(*), intent(in) :: s + read (s, *) str2int + end function + + pure recursive integer function gcd2(a, b) result(GCD) + integer, intent(in) :: a, b + if (b == 0) then + GCD = a + else + GCD = gcd2(b, mod(a, b)) + end if + end function gcd2 + + pure integer function gcdn(n) + integer, intent(in) :: n(:) + integer :: i + gcdn = n(1) + do i = 2, size(n) + gcdn = gcd2(gcdn, n(i)) + end do + end function + +end program -- cgit v1.2.3