Skip to content

Instantly share code, notes, and snippets.

@uggds
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uggds/87edb74aaa3ac8711cf5 to your computer and use it in GitHub Desktop.
Save uggds/87edb74aaa3ac8711cf5 to your computer and use it in GitHub Desktop.
Collatz問題
module m_collatz
implicit none
contains
recursive function icollatz(n) result(result)
integer, intent(in) :: n
integer, allocatable :: result(:)
if (n == 1) then
result = [1]
else if (mod(n, 2) == 0) then ! even
result = [n, icollatz(n / 2)]
else ! odd
result = [n, icollatz(3 * n + 1)]
end if
return
end function icollatz
end module m_collatz
!===========================
program main
use m_collatz
implicit none
integer :: i, target, maxStep
integer, allocatable :: m(:)
integer t1, t2, t_rate, t_max, diff
call system_clock(t1) ! 開始時を記録
target = 1
maxStep = 1
!$omp parallel shared(maxStep), private(m)
!$omp do
do i = 1, 10**5
m = icollatz(i)
if (maxStep < size(m)) then
maxStep = max(maxStep, size(m))
target = i
end if
end do
!$omp end do
!$omp end parallel
print "(2i10, ' step')", target, maxStep
call system_clock(t2, t_rate, t_max) ! 終了時を記録
if ( t2 < t1 ) then
diff = t_max - t1 + t2
else
diff = t2 - t1
endif
print "(a, f10.3)", "time it took was:", diff/dble(t_rate)
stop
end program main
@uggds
Copy link
Author

uggds commented Nov 24, 2014

 77031       351 step

time it took was: 3.073

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment