n = gets.to_i arr = (1..n).to_a.map { |i| i.digits(2).count(1) } INF = 10000000 dp = [INF] * n dp[0] = 1 # p arr que = [] # queueの中身は[現在のマス, 移動数] que.unshift([0, 1]) while !que.empty? index, move_count = que.pop() if index == n-1 puts move_count exit 0 end if index + arr[index] <= n - 1 que.unshift([index + arr[index], move_count + 1]) end if index - arr[index] >= 0 que.unshift([index - arr[index], move_count + 1]) end end puts -1