diff src/collatz.f @ 0:307a81e46071 tip

initial committ
author Robert McIntyre <rlm@mit.edu>
date Tue, 18 Oct 2011 01:17:49 -0700
parents
children
line wrap: on
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/collatz.f	Tue Oct 18 01:17:49 2011 -0700
     1.3 @@ -0,0 +1,52 @@
     1.4 +      program collatz
     1.5 +      implicit none
     1.6 +      character (len = 100) :: file_name  
     1.7 +      integer, parameter :: big = selected_int_kind(11)
     1.8 +      integer  :: n
     1.9 +      call getarg( 1, file_name )  
    1.10 +      OPEN(unit = 7, file = file_name)
    1.11 +      read (7,*) n
    1.12 +      write (unit = *, fmt = "(I0)") search_collatz(n)
    1.13 +
    1.14 +      contains
    1.15 +
    1.16 +      function collatz_next (n) result (r)
    1.17 +      implicit none
    1.18 +      integer (kind = big)  :: r,n
    1.19 +      if (0 == mod(n,2)) then
    1.20 +         r = n/2
    1.21 +      else
    1.22 +         r = 1 + 3*n
    1.23 +      end if 
    1.24 +      end function collatz_next
    1.25 +      
    1.26 +      function collatz_length (n) result (r)
    1.27 +      implicit none
    1.28 +      integer (kind = big)  :: t
    1.29 +      integer :: n,r
    1.30 +      r = 1
    1.31 +      t = n
    1.32 +      do 
    1.33 +         if (1 == t) then
    1.34 +         exit
    1.35 +         end if
    1.36 +         r = r + 1
    1.37 +         t = collatz_next(t)
    1.38 +      end do
    1.39 +      end function collatz_length
    1.40 +      
    1.41 +      function search_collatz (n) result (r)
    1.42 +      implicit none
    1.43 +      integer n,r,i,max,max_val,temp_val
    1.44 +      integer (kind = big) :: t
    1.45 +      t = n
    1.46 +      do i = 1,n-1
    1.47 +         temp_val = collatz_length(i)
    1.48 +         if (temp_val > max_val) then
    1.49 +         max = i
    1.50 +         max_val = temp_val
    1.51 +      end if
    1.52 +      end do
    1.53 +      r = max
    1.54 +      end function search_collatz
    1.55 +      end program collatz