logical function is_reacheable(n) implicit none integer::i, n logical::is_reacheablef=.false. if (n.eq.1) then is_reacheablef = .true. return end if do i=max(1,n-(31-LEADZ(10000))), n if (n.eq.POPCNT(i)+i) then is_reacheable = .true. exit end if end do end function is_reacheable recursive function progress(pos, goal, step) result(total_step) implicit none logical,save::reached=.false. integer::pos, goal, step integer::popcount integer::total_step if (pos .eq. goal) then total_step = step return else popcount = POPCNT(pos) if (pos + popcount .le. goal) then total_step = progress(pos + popcount, goal, step + 1) else if (pos - popcount .ge. 1) then total_step = progress(pos - popcount, goal, step + 1) end if end if end function progress program main implicit none interface logical function is_reacheable(n) integer::n end function is_reacheable recursive function progress(pos, goal, step) result(total_step) integer::pos, goal, step integer::total_step end function progress end interface integer::N,total_step read *,N if(is_reacheable(N).eqv..false.) then print '(a)',"-1" return endif total_step = progress(1, N, 1) print '(i0)', total_step end program main