{.checks: off, optimization: speed.} import strutils, sequtils, queues proc popcount(x: int): cint {. importc: "__builtin_popcount", nodecl, nosideeffect.} let N = stdin.readline.parseInt var dist = newSeqWith(N+1, -1) que = initQueue[(int, int)]() que.add((1, 1)) while que.len > 0: let (c, v) = que.pop if dist[v] != -1: continue dist[v] = c if v == N: echo(c) quit() let pcnt = popcount(v) for sgn in @[-1, 1]: if 0 < v + sgn * pcnt and v + sgn * pcnt <= N and dist[v + sgn * pcnt] == -1: que.add((dist[v] + 1, v + sgn * pcnt)) echo(-1)