summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorIgor Pashev <pashev.igor@gmail.com>2011-06-26 14:15:39 +0400
committerIgor Pashev <pashev.igor@gmail.com>2011-06-26 14:15:39 +0400
commit56d6ccc17a39361ede9bf1a4d6810690b76cda2b (patch)
tree2da3c5c54f1a8213997cbd0a1fa2f5bdc37b1500
parent6896c7ab5b873d6103af5181501e9e78fd5b25d3 (diff)
downloadgcd-56d6ccc17a39361ede9bf1a4d6810690b76cda2b.tar.gz
Fortran 2003
-rw-r--r--gcd.f0357
1 files changed, 57 insertions, 0 deletions
diff --git a/gcd.f03 b/gcd.f03
new file mode 100644
index 0000000..f1f144f
--- /dev/null
+++ b/gcd.f03
@@ -0,0 +1,57 @@
+! 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