n = gets.to_i $nmoves = [] $bc = [] def bitcount(i) $bc[i] ||= i.to_s(2).count('1') end def move_from(i, n) return unless $nmoves[i] fwd = i + bitcount(i) $nmoves[fwd] = $nmoves[i] + 1 if fwd <= n back = i - bitcount(i) return if (back < 1) || $nmoves[back] $nmoves[back] = $nmoves[i] + 1 move_from(back, n) end $nmoves[1] = 1 1.upto(n-1) do |i| move_from(i, n) end puts $nmoves[n] || -1