I have solved Euler 14 problem in Python, and I wanted to see how much time it would take for the same calculation to take place in Fortran. In python, I wrote:
def main(n):
'''Counts the elements of the sequence starting at n and finishing at 1 '''
count = 1
while True:
if n == 1:
return count
if (n % 2 == 0):
n = n/2
else:
n = 3*n + 1
count += 1
if __name__ == '__main__':
limit = 10**6
# limit = 14
n = 1
result = 0
while n < limit:
sequence = main(n)
if sequence > result:
result = sequence
solution = n
n += 1
print("Number that gives the longest chain: ", solution)
This works well but it is not very efficient (it takes about 23 seconds to complete). I wanted to see how long it would take for the same calculation in Fortran. Then I wrote the same in Fortran (below). However, in the do while loop in the main programme, the value of n does not go above 2.
subroutine euler14(n,counter)
integer :: n, counter
counter = 1
do
if (n.eq.1) EXIT
!end if
if (mod(n,2).eq.0) then
n = n/2
else
n = 3*n + 1
end if
counter = counter + 1
!print *, "Counter: ", counter
end do
!print *, 'Made it'
RETURN
end
program main
implicit none
integer, parameter :: limit = 1000000
integer :: n, counter,solution,rf
real :: start_time, stop_time
call cpu_time(start_time)
n = 1
rf = 0 ! result
do while(n.lt.limit)
!print *, n
call euler14(n,counter)
if(counter.gt.rf) then
rf = counter
solution = n
end if
n = n + 1
end do
call cpu_time(stop_time)
print *, "Time taken: ",
a stop_time - start_time, " seconds."
end program main
Do you have any idea of what it could've gone wrong with my programme in Fortran?
Many thanks in advance