Mercurial > coderloop
comparison 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 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:307a81e46071 |
---|---|
1 program collatz | |
2 implicit none | |
3 character (len = 100) :: file_name | |
4 integer, parameter :: big = selected_int_kind(11) | |
5 integer :: n | |
6 call getarg( 1, file_name ) | |
7 OPEN(unit = 7, file = file_name) | |
8 read (7,*) n | |
9 write (unit = *, fmt = "(I0)") search_collatz(n) | |
10 | |
11 contains | |
12 | |
13 function collatz_next (n) result (r) | |
14 implicit none | |
15 integer (kind = big) :: r,n | |
16 if (0 == mod(n,2)) then | |
17 r = n/2 | |
18 else | |
19 r = 1 + 3*n | |
20 end if | |
21 end function collatz_next | |
22 | |
23 function collatz_length (n) result (r) | |
24 implicit none | |
25 integer (kind = big) :: t | |
26 integer :: n,r | |
27 r = 1 | |
28 t = n | |
29 do | |
30 if (1 == t) then | |
31 exit | |
32 end if | |
33 r = r + 1 | |
34 t = collatz_next(t) | |
35 end do | |
36 end function collatz_length | |
37 | |
38 function search_collatz (n) result (r) | |
39 implicit none | |
40 integer n,r,i,max,max_val,temp_val | |
41 integer (kind = big) :: t | |
42 t = n | |
43 do i = 1,n-1 | |
44 temp_val = collatz_length(i) | |
45 if (temp_val > max_val) then | |
46 max = i | |
47 max_val = temp_val | |
48 end if | |
49 end do | |
50 r = max | |
51 end function search_collatz | |
52 end program collatz |